c# 6.0 特性

  1. Auto-property initializers 自动属性初始化器
    public int B { get; set; } = 1;
    public string SeparatorSpaces { get; } = string.Empty;

  2. 字符串嵌入值 (String interpolation)
    return $"({X}, {Y})";//其中X,Y为变量名

  3. Expression-bodied members 表达式体成员
    public double Value => (double)A / B;
    public void Print(string s) => MessageBox.Show(s);
    public int this[int index] => index == 0 ? A : B;
    只读属性,只读索引器和方法都可以使用Lambda表达式作为Body。

  4. nameof operator nameof 运算符
    throw new ArgumentNullException(nameof(separatorSpaces));
    nameof会返回变量,参数或成员名。
    这个很有用,原来写WPF中的ViewModel层的属性变化通知时,需要写字符串,或者使用MvvmLight等库中的帮助方法,可以传入获取属性的Lambda,但由于是在运行时解析,会有少许性能损失。现在好了,使用nameof运算符,既能保证重构安全和可读性,又能保证性能。

  5. Dictionary initializer 字典初始化器
    Dictionary<string, Fraction> CommonFractions =
    new Dictionary<string, Fraction>
    {
    [“zero”] = new Fraction(),
    [“one”] = new Fraction(1, 1),
    [“half”] = new Fraction(1, 2),
    [“quarter”] = new Fraction(1, 4),
    [“infinity”] = new Fraction(1, 0),
    };

  6. Exception filters 异常过滤器
    try
    {
    Fraction fraction = new Fraction(1, 2, null);
    }
    catch (ArgumentNullException e) when (e.ParamName == “separatorSpaces”)
    {
    MessageBox.Show(“separatorSpaces can not be null”);
    }

  7. Null propagation 空传播 (?)
    a. 如果对象为NULL,则不进行后面的获取成员的运算,直接返回NULL
    b. 可以用于方法调用
    List li = null;
    li?.Add(“abc”);
    c. 也可以用于数组索引器
    User[] users = null;
    List listUsers = null;

// Console.WriteLine(users[1]?.Name); // 报错
// Console.WriteLine(listUsers[1]?.Name); //报错

Console.WriteLine(users?[1].Name); // 正常
Console.WriteLine(listUsers?[1].Name); // 正常

  1. Using static members using静态导入
    在using中可以指定一个静态类,然后可以在随后的代码中直接使用该类的静态方法
发布了54 篇原创文章 · 获赞 14 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/bayinglong/article/details/90664388