昨日更新了VS2015,今日学习了C#6 新增的几个特性,特记录下来,增强记忆。
1.自动的属性初始化器(Auto Property Initialzier)
1 public class AutoProperBeforCsharp6 2 { 3 private string _property = string.Empty; 4 public string Property 5 { 6 get; set; 7 } 8 public AutoProperBeforCsharp6(string value) 9 { 10 Property = value; 11 } 12 } 13 14 public class AutoPropertyInCsharp6 15 { 16 public string Property { get; } = string.Empty; 17 }
2.主构造器
1 public class PrimaryConstructorBeforeCsharp6 2 { 3 public string Name { get; set; } 4 public string Value { get; set; } 5 public PrimaryConstructorBeforeCsharp6(string name, string value) 6 { 7 Name = name; 8 Value = value; 9 } 10 } 11 12 public class PrimaryConstructorInCsharp6(string name,string value) 13 { 14 public string Name { get; set; } = name; 15 public string Value { get; set; } = value; 16 }
3.字典初始化器
1 public class DictionaryInitialzierBeforeCsharp6 2 { 3 public Dictionary<string, string> dic = new Dictionary<string, string>() 4 { 5 { "name","zhangsan"}, 6 { "age","18"} 7 }; 8 } 9 10 public class DictionaryInitialzierInCsharp6 11 { 12 public Dictionary<string, string> dic = new Dictionary<string, string>() 13 { 14 ["name"] = "zhangsan", 15 ["age"] = "18" 16 }; 17 }
4.异常过滤器
//Before C# 6 //示例 1 try { //Some code } catch (Exception ex) { if(ex.InnerException != null) { //Do work; } } //In C# 6 try { //Some code } catch (Exception ex) if (ex.InnerException == null) { //Do work }
5. 用于检查Null值得条件运算符
1 //Before C# 6 2 var userRank = "No Rank"; 3 if(UserID != null) 4 { 5 userRank = Rank; 6 } 7 8 //or 9 10 var userRank = UserID != null ? Rank : "No Rank" 11 12 13 14 //In C# 6 15 var userRank = UserID?.Rank ?? "No Rank";
6.用Lamda作为函数体 Expression bodies on Method-like members
1 public class UserBeforeCsharp6 2 { 3 public int Id { get; } 4 public String Name { get; set; } 5 public override string ToString() 6 { 7 return $"Id:{Id} Name:{Name}"; 8 } 9 } 10 11 12 //After 13 public class UserInCsharp6 14 { 15 public int Id { get; } 16 public String Name { get; set; } 17 public override string ToString() => $"Id:{Id} Name:{Name}"; 18 }
7. 无参数的结构体构造函数 Parameterless Constructors in Struct