C# 6.0语法糖

自动属性默认初始化
public string Name { get; set; } = "hello world";

Null条件运算符
Customer customer = new Customer();
 string name3 = customer?.Name;

字符串格式化
var s = $"{p.Name} is {p.Age} year{(p.Age == 1 ? "" : "s")} old";

索引初始化
var numbers = new Dictionary<int, string> {[7] = "seven",[9] = "nine",[13] = "thirteen" };

异常过滤器when
try 
{ 
throw new ArgumentException("string error");
 }
 catch (ArgumentException e) when (myfilter(e))
 { 
Console.WriteLine(e.Message);
 }

static bool myfilter(ArgumentException e)
 { 
return false;
 }

when语法作用是:在进入到catch之前、验证when括号里myfilter方法返回的bool,如果返回true继续运行,false不走catch直接抛出异常。

nameof表达式
string name = "";
Console.WriteLine(nameof(name));
当如下使用的时候,编译器会只取最后的ZipCode。
nameof(person.Address.ZipCode)

  

posted @ 2018-01-31 15:36  会弹猫的吉他  阅读(119)  评论(0编辑  收藏  举报