1、使用null條件運算符,在調(diào)用對象的屬性或者方法時,我們通常需要檢查對象是否為null,現(xiàn)在你不需要寫一個if語句,我們提供更便捷的方法,下面的代碼獲取list中元素的數(shù)量,當list本身為null時,Count方法也將返回null值。
public int? GetListItemCount(List list)
{
return list?.Count()
;}
2、使用新增的nameof關鍵字獲取參數(shù)、成員和類型的字符串名稱。比個例子:當需要知道變量名的字符串表示形式時,我們可以這樣寫:
DateTime currentDate =DateTime.Now;Console.
WriteLine("{0}={1}",nameof(currentDate), currentDate);
輸入結(jié)果如下所示,nameof關鍵字將變量名作為字符串形式直接輸出:
currentDate=2014/12/8 21:39:53
3、在字符串中直接插入變量,而不需要在字符串格式化語句中寫形如{n}的格式化模板,如下的代碼輸出:“零度編程,歡迎您!”
string siteName ="零度編程";
string welcome = $"{siteName},歡迎您!";
4、Lambda表達式可以作為方法體或者屬性的實現(xiàn),我們可以直接將一個表達式賦予一個方法或者屬性。
public class Book
{
public decimal Price {get;set; }
public int Count {get;set; }
public decimal GetTotalPrice() =>this.Price *this.Count;
}
public class Book
{
public decimal Price {get;set; }
public int Count {get;set; }
public decimal TotalPrice =>this.Price *this.Count;
}
5、在這之前,如果您要初始化對象的一個屬性或者給屬性賦默認值,需要定義一個私有字段,給私有字段賦初始值,現(xiàn)在可以這樣寫:
public class Book
{
public decimal Price {get;set; } = 0m;
public int Count {get;set; } = 10;
}
6、在新的C#6.0種提供了對象索引初始化的新方法,現(xiàn)在初始化一個對象的索引可以這樣:
var myObject =new MyObject
{?
? ["Name001"] ="零度",?
? ["Name002"] ="編程",
? ["Name003"] ="網(wǎng)站"
};
7、在對一個異常進行catch捕獲時,提供一個篩選器用于篩選特定的異常,這里的if就是一個篩選器,示例代碼如下:
try{
throw new ArgumentNullException("bookName");
}catch (ArgumentNullException e)
if(e.ParamName =="bookName")
{
Console.WriteLine("bookName is null !");
}
8、靜態(tài)引用,在這之前通過using關鍵字可引用命名空間,現(xiàn)在你可以通過using引用一個類,通過using引用的類,在代碼中可不寫類名,直接訪問靜態(tài)屬性和方法。
using System.IO.File;namespace Test
{
public class MyClass
? ? {
??? public void CreateTextFile(string fileName)? ??
{? ? ? ? ? ?
?????????????? CreateText(fileName);? ? ?
? }? ?
}
}
上面代碼中CreateText屬于System.IO命名空間下File靜態(tài)類的方法,由于我們使用了using靜態(tài)引入了類File,所以可直接使用方法名,而不需要File.CreateText(fileName)這樣寫。
9、這是另一個和異常相關的特性,使得我們可以在catch 和finally中等待異步方法,看微軟的示例:
try{
? res =awaitResource.OpenAsync(“myLocation”);// You could do this.
}
catch (ResourceException e)
{
? awaitResource.LogAsync(res, e);// Now you can do this. }finally{
? if(res !=null)
? awaitres.CloseAsync();// … and this.
}
10、在之前,結(jié)構(gòu)struct不允許寫一個無參構(gòu)造函數(shù),現(xiàn)在您可以給結(jié)構(gòu)寫一個無參構(gòu)造函數(shù),當通過new創(chuàng)建結(jié)構(gòu)時構(gòu)造函數(shù)會被調(diào)用,而通過default獲取結(jié)構(gòu)時不調(diào)用構(gòu)造函數(shù)。
11、使用Visual Studio 2015 創(chuàng)建項目時,不但可選擇.NET Framework的版本,現(xiàn)在也可選擇C#語言的版本。
12、對字典的初始化,提供新的方法,在新版本的C#6中可使用如下的方式初始化一個字典。
Dictionary siteInfos = new Dictionary()
{
? ? { "SiteUrl", "www.xcode.me" },
? ? { "SiteName", "零度編程" },
? ? { "SiteDate", "2013-12-09" }
};
13、新的代碼編輯器提供更好的體驗,集成最新名為Roslyn的編譯器,一些新的特性讓您對這款編輯器愛不釋手,最新的VisualStudio
2015中新增了一個燈泡功能,當您的代碼中存在需要修復的問題或者需要重構(gòu)時,代碼行的左邊將顯示一個小燈泡,點擊小燈泡后編輯器將幫助您自動修復和重構(gòu)現(xiàn)有代碼。
來源:零度編程