C#6.0新語法示例詳解
前言
一直用C#開發(fā)程序,.NET的功能越來越多,變化也挺大的,從最初的封閉,到現(xiàn)在的開源,功能不斷的增加,一直在進(jìn)步。下面就來給大家詳細(xì)介紹下C#6.0新語法的相關(guān)內(nèi)容,一起來看看吧
眾所周知,c# 6.0 是在visual studio 2015中引入的。在其他的幾個(gè)版本中同樣引入一些特性,比如在c# 3.0中引入了linq,在c# 4.0中引入了動(dòng)態(tài)類型dynamic,在c#5.0中引入async和await等等。
在c# 6.0更多關(guān)注了語法的改進(jìn),而不是增加新的功能。這些新的語法將有助于我們更好更方便的編寫代碼。
1、自動(dòng)只讀屬性
之前屬性為如下所示,屬性賦值需在構(gòu)造函數(shù)對(duì)其初始化
1 public int Id { get; set; } 2 public string Name { get; set; }
更新后
public string Name { get; set; } = "summit"; public int Age { get; set; } = 22; public DateTime BirthDay { get; set; } = DateTime.Now.AddYears(-20); public IList<int> AgeList { get; set; } = new List<int> { 10, 20, 30, 40, 50 };
2、直接引用靜態(tài)類
如果之前調(diào)用靜態(tài)類中的方法,如下書寫:
Math.Abs(20d);
更新后:
using static System.Math; private void Form1_Load(object sender, EventArgs e) { Abs(20d); }
3、Null 條件運(yùn)算符
之前在使用對(duì)象時(shí),需要先進(jìn)性判斷是否為null
if (student!=null) { string fullName = student.FullName; } else { //…… }
更新后:
string fullName = student?.FullName; //如果student為空則返回Null,不為空則返回.FullNaem,注意!得到的結(jié)果一定是要支持null
4、字符串內(nèi)插
string str = $"{firstName}和{lastName}"
5、異常篩選器
try { } catch(Exception e) when(e.Message.Contains("異常過濾,把符合條件的異常捕獲") { }
6、nameof 表達(dá)式可生成變量、類型或成員的名稱作為字符串常量
Console.WriteLine(nameof(System.Collections.Generic)); // output: Generic Console.WriteLine(nameof(List<int>)); // output: List
7、使用索引器初始化對(duì)字典進(jìn)行賦值
Dictionary<int, string> messages = new Dictionary<int, string> { { 404, "Page not Found"}, { 302, "Page moved, but left a forwarding address."}, { 500, "The web server can't come out to play today."} };
同時(shí)也可以這樣通過索引的方式進(jìn)行賦值
Dictionary<int, string> webErrors = new Dictionary<int, string> { [404] = "Page not Found", [302] = "Page moved, but left a forwarding address.", [500] = "The web server can't come out to play today." };
8、在屬性/方法里面使用Lambda表達(dá)式
public string NameFormat => string.Format("姓名: {0}", "summit"); public void Print() => Console.WriteLine(Name);
總結(jié)
到此這篇關(guān)于C#6.0新語法的文章就介紹到這了,更多相關(guān)C#6.0新語法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C# 獲取進(jìn)程退出代碼的實(shí)現(xiàn)示例
這篇文章主要介紹了C# 獲取進(jìn)程退出代碼的實(shí)現(xiàn)示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-02-02C#實(shí)現(xiàn)向函數(shù)傳遞不定參數(shù)的方法
這篇文章主要介紹了C#實(shí)現(xiàn)向函數(shù)傳遞不定參數(shù)的方法,涉及C#操作函數(shù)參數(shù)的相關(guān)技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-04-04利用C#編寫一個(gè)Windows服務(wù)程序的方法詳解
這篇文章主要為大家詳細(xì)介紹了如何利用C#編寫一個(gè)Windows服務(wù)程序,文中的實(shí)現(xiàn)方法講解詳細(xì),具有一定的參考價(jià)值,感興趣的可以了解一下2023-03-03

C#使用foreach遍歷哈希表(hashtable)的方法