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

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

3.导入静态类(Using Static)

像之前使用Math这个静态类的时候要先导入System命名空间后才能使用它.现在可以直接导入这个静态,然后代码中直接使用其函数.

 

复制代码 using static System.Math;//注意这里不是命名空间哦
 
Console.WriteLine($"之前的使用方式: {Math.Pow(4, 2)}");
Console.WriteLine($"导入后可直接使用方法: {Pow(4,2)}");

 

注意这里是using static ...
如果某个命名空间下有n个方法,用这种方式直接引入单个静态类而不用引用所有方法还是挺方便的.

4.空值运算符(Null-conditional operators)

之前写过无数个这样的判断代码

 

复制代码 if (*** != null)
{
     //不为null的操作
}
return null;

 

现在使用可以简化这样方式.

 

复制代码 var age = account.AgeList?[0].ToString();
 
Console.WriteLine("{0}", (person.list?.Count ?? 0));

 

如果account.AgeList为空则整个表达式返回空,否则后边的表达式的值.

5.对象初始化器(Index Initializers)

这种方式可以给字典或其他对象通过索引赋值初始化.

 

复制代码 IDictionary<int, string> dict = new Dictionary<int, string>() {
       [1]="first",
       [2]="second"
};
foreach(var dic in dict)
{
    Console.WriteLine($"key: {dic.Key} value:{dic.Value}");
}

 

output:
key: 1 value:first
key: 2 value:second

6.异常过滤器(Exception filters)

 

复制代码 private static bool Log(Exception e)
{
    Console.WriteLine("log");
    return true;