自动属性默认初始化
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)