最近在看《C#高級編程 C# 6&.NET Core 1.0》,會做一些讀書筆記,也算對知識的總結與沉淀了。
1.靜態的using聲明
靜態的using聲明允許調用靜態方法時不使用類名:
1 // C# 5 2 using System; 3 4 Console.WriteLine("C# 5"); 5 6 // C# 6 7 using static System.Console; 8 9 WriteLine("C# 6");
2.表達式體方法
表達式體方法只包含一個可以用Lambda語法編寫的語句:
1 // C# 5 2 public bool IsSquare(Rectangle rect) 3 { 4 return rect.Width == rect.Height; 5 } 6 7 // C# 6 8 public bool IsSquare(Rectangle rect) => rect.Width == rect.Height;
3.表達式體屬性
與表達式體方法類似,只有get存儲器的單行屬性可以用Lambda語法編寫:
1 // C# 5 2 public string FullName 3 { 4 get 5 { 6 return FirstName + " " + LastName; 7 } 8 } 9 10 // C# 6 11 public string FullName => FirstName + " " + LastName;
4.自動實現的屬性初始化器
自動實現的屬性可以用屬性初始化器來初始化:
1 // C# 5 2 public class Person 3 { 4 public Person() 5 { 6 Age = 24; 7 } 8 public int Age { get; set; } 9 } 10 11 // C# 6 12 public class Person 13 { 14 public int Age { get; set; } = 24; 15 }
5.只讀的自動屬性
1 // C# 5 2 private readonly int _bookId; 3 public BookId 4 { 5 get 6 { 7 return _bookId; 8 } 9 } 10 11 // C# 6 12 private readonly int _bookId; 13 public BookId { get; }
6.nameof運算符
使用新的nameof運算符,可以訪問字段名、屬性名、方法名和類型名。這樣,在重構時就不會遺漏名稱的改變:
1 // C# 5 2 public void Method(object o) 3 { 4 if(o == null) 5 { 6 throw new ArgumentNullException("o"); 7 } 8 } 9 10 // C# 6 11 public void Method(object o) 12 { 13 if(o == null) 14 { 15 throw new ArgumentNullException(nameof(o)); 16 } 17 }
7.空值傳播運算符
空值傳播運算符簡化了空值的檢查:
1 // C# 5 2 int? age = p == null ? null : p.Age; 3 4 // C# 6 5 int? age = p?.Age;
8.字符串插值
字符串插值刪除了對string.Format的調用,它不在字符串中使用編號的格式占位符,占位符可以包含表達式:
1 // C# 5 2 public override string ToString() 3 { 4 return string.Format("{0},{1}", Title, Publisher); 5 } 6 7 // C# 6 8 public override string ToString() => $"{Title}{Publisher}";
9.字典初始化
1 // C# 5 2 var dic = new Dictionary<int, string>(); 3 dic.Add(3, "three"); 4 dic.Add(7, "seven"); 5 6 // C# 6 7 var dic = new Dictionary<int, string>() 8 { 9 [3] = "three", 10 [7] = "seven" 11 };
10.異常過濾器
異常過濾器允許在捕獲異常之前過濾它們:
1 // C# 5 2 try 3 { 4 // 5 } 6 catch (MyException ex) 7 { 8 if (ex.ErrorCode != 405) throw; 9 } 10 11 // C# 6 12 try 13 { 14 // 15 } 16 catch (MyException ex) when (ex.ErrorCode == 405) 17 { 18 // 19 }
11.catch中的await
await現在可以在catch子句中使用,C# 5需要一種變通方法:
1 // C# 5 2 bool hasError = false; 3 string errorMsg = null; 4 try 5 { 6 // 7 } 8 catch (MyException ex) 9 { 10 hasError = true; 11 errorMsg = ex.Message; 12 } 13 if (hasError) 14 { 15 await new MessageDialog().ShowAsync(errorMsg); 16 } 17 18 // C# 6 19 try 20 { 21 // 22 } 23 catch (MyException ex) 24 { 25 await new MessageDialog().ShowAsync(ex.Message); 26 }