C#6.0中10大新特性的应用和总结

2019-12-30 11:56:59刘景俊

}
static void TestExceptionFilter()
{
    try
    {
        Int32.Parse("s");
    }
    catch (Exception e) when (Log(e))
    {
        Console.WriteLine("catch");
        return;
    }
}

 

当when()里面返回的值不为true,将持续抛出异常,不会执行catch里面的方法.

7.nameof表达式 (nameof expressions)

在对方法参数进行检查时经常这样写:

 

复制代码 private static void Add(Account account)
{
     if (account == null)
         throw new ArgumentNullException("account");
}

 

如果某天参数的名字被修改了,下面的字符串很容易漏掉忘记修改.
使用nameof表达式后,编译的时候编译器将检查到有修改后自动导航与重构(-_-! 不知道翻译的对不对)

 

复制代码 private static void Add(Account account)
{
     if (account == null)
         throw new ArgumentNullException(nameof(account));
}

 

8.在cath和finally语句块里使用await(Await in catch and finally blocks)

c#5.0里是不支持这么写.

 

复制代码 Resource res = null;
try
{
    res = await Resource.OpenAsync(…);       // You could do this.
    …
}
catch(ResourceException e)
{
    await Resource.LogAsync(res, e);         // Now you can do this …
}
finally
{
    if (res != null) await res.CloseAsync(); // … and this.
}

 

9.在属性里使用Lambda表达式(Expression bodies on property-like function members)

 

复制代码