C# 6 的新特性
還是記錄一下吧,好記性不如爛筆頭。
1、靜態(tài)的 using 聲明
靜態(tài)的 using 聲明允許條用方法時候不適用類名。
C# 5:
using System; //etc Console.WriteLine("Hello,World!");C# 6:
using static System.Console; //etc. Writeline("Hello,World");2、表達式體方法
表達式體方法只包括一個可以用 lambda語法編寫語句:
C# 5:
public bool IsSquare(Rectangle rect) {return rect.Height == rect.Width; }C# 6:
public bool IsSquare (Rectangle rect) => rect.Height == rect.Width;3、表達式體屬性?
與表達式體方法類似,只有get存取器的單行屬性可以用lambda語法編寫:
C# 5
public string FullName {get{return FirstName + "" + LastName;} }C# 6
public string FullName => FirstName + "" +LastName;4、自動實現(xiàn)的屬性初始化器
自動實現(xiàn)的屬性可以用屬性初始化器來初始化:
C# 5
public class Person {public Person(){Age = 24;}public int Age { get;set;} }? ? ? ? ? C# 6
public class Person {public int Age {get;set;} = 42; }5、只讀的自動屬性
?為了實現(xiàn)只讀屬性,C# 5 需要使用完整的屬性語法:而在C# 6中,可以使用自動實現(xiàn)的屬性:
C# 5
private readonly int _bookId;public BooKId {get{ret _bookId;} }?C# 6
public BookId {get;}6、nameof 運算符
使用新的nameof運算符,可以訪問字段名、屬性名、方法名或者類型名。這樣,在重構時,就不會遺漏名稱的改變:
C# 5
public void Method( object o ) {if( o == null) throw new ArgumentNullException("o"); }?C# 6
public void Method (object o) {if(o == null) throw new ArgumentNullException (nameof(0)); }7、?空值傳播運算符
空值傳播運算符簡化了空值的檢查:
C#? 5
int? age = p == null ? null : p.Age;?C# 6
int? age = p?.Age;? ? ? ? ? ?新語法也有觸發(fā)事件的優(yōu)點:
? ? ? ? ? ?C# 5
var handler = Event; if(handler != null) {handler(source,e); }C# 6
handler?.Invoke(source,e);8、字符串插值
字符串插值刪除了對 string.Format的調用,它不在字符串中使用編號的格式占位符,占位符可以包含表達式:
C# 5
public override ToString() {return string.Format("{0},{1}",Title,Publisher); }?C#? 6
public override ToString() => $"{Title} {Publisher}";9、字典初始化器
字典現(xiàn)在可以用字典初始化器來初始化,類似于集合初始化器。
C#? 5
var dict = new Dictionary<int , string>(); dict.Add(3,"three"); dict.Add(7,"seven");? ? ? ? ? C# 6
var dict = new Dictionary <int ,string>() {[3] = "three",[7] = "seven" }10、異常過濾器
異常過濾器允許在捕獲異常之前過濾他們。
C# 5
try {//etc. } catch (MyException ex) {if(ex.ErrorCode != 405) throw; }? ? ? ? ? ?C# 6
try {//etc. } catch (MyExctption ex) when (ex.ErrorCode == 405) {//etc. }新語法的優(yōu)勢是,它不僅減少了代碼額的長度,而且沒有改變堆棧跟蹤 -------在 C# 5 中會改變堆棧跟蹤。
11、Catch 中的 await
await 現(xiàn)在可以在catch子句中使用。C# 5需要一種變通方法:
C# 5
bool hasError = false; string errorMessage = null; try {//etc. } catch (MyException ex) {hasError = true;errorMessage = ex.Message; } if(hasError) {await new MessageDialog().ShowAsync(errorMessage); }? ? ? ? ? ?C#? 6
try {//etc. } catch (MyException ex) {await new MessageDialog().ShowAsync(ex.Message); }?
?
?
?
?
?
?
?
?
總結
- 上一篇: ASP.NET MVC 使用Log4Ne
- 下一篇: Xshell连接远程Linux服务器失败