.NET/C# 各版本变化及衍生知识点 C# 6.0

一、 C# 6.0,对应.NET 4.6,对应VS 2015,新特性:主构造函数、using静态类、属性表达式、方法表达式、枚举参数、null判断、Constructor type parameter inference、内联out、自动属性增强、字符串嵌入值string.Format变成直接"{变量}"、nameof表达式、异常过滤器、catch和finally 中的 await 、无参数的结构体构造函数

1、字符串嵌入值

这个Resharper有自动提示,可以自动转换,但怕技术太新,不好移植,还是暂时没在项目中用

string a = string.Format("ab{0}d", "X");
Console.WriteLine(a);
string x = "X";
string b = $"ab{x}d";
Console.WriteLine(b);
Console.ReadKey();

在字符串前面加$,中间用{},里面可以放变量或字符串,简洁了很多。

2、主构造函数

public class Point {
    private int x, y;

    public Point(int x, int y)
        this.x = x;
        this.y = y;
    }
}

//等效
public class Point(int x, int y) {
    private int x, y;
}

3、自动属性赋值

   class Point
    {
        public int X { get; private set; }
        public int Y { get; private set; }

        public Point()
        {
            this.X = 100;
            this.Y = 100;
        }
    } 

   //等效
   class Point
    {
        public int X { get; private set; } = 100;
        public int Y { get; private set; } = 100;
    } 

4、引用静态类

以前要Math.Round(1.2),每次用到都要Math,现在可以先引用(using System.Math;),然后每次直接Round()就可以

5、属性表达式/方法表达式

public double Distance
{
    get {return 1;}
}
//等效
public double Distance1 => 1;
public DayOfWeek day(int i)
{
    return DayOfWeek.Friday;
}
//等效
public DayOfWeek day1(int i) => DayOfWeek.Friday;
public class Point
{
    public int X{get;} = 2;
    public int Y{get;} = 1;
    public double Dist => Math.Sqrt(X*X + Y*Y);
    public override string ToString() => $"({X}, {Y})";
}

总之就是各种简化。一般可以按原先习惯方法写,然后用Resharper之类的插件,自动简化成最新版的

6、null检查运算符

string a = null;
//string x=a.ToString(); //会报错
//Console.WriteLine(x);
string y=a?.ToString();
Console.WriteLine(y);
Console.ReadKey();

以前在调用方法前,时不时要判断是不是空,比如常见的ToString(),一般要用Convert.ToString(),不然容易报错,现在只要使用?.ToString()就可以了

7、内联out

int x;
int.TryParse("123", out x);
//等效
int.TryParse("123", out int x);

因为out在使用前必须定义,但定义了又没用,反正值要在方法里面改的,所以就可以直接合并起来用

8、NameOf表达式

public static void AddCustomer(Customer customer)
{
    if (customer == null)
    {
        throw new ArgumentNullException(nameof(customer));
    }
}

改名的时候会一起更新,没用过,记录一下。

9、try/catch/finally改进

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. 
}

在catch/finally中增加await

try { … } 
catach ( CustomException ex ) if ( CheckException(ex) ) 
{ … }  

原先要在catch里面判断,现在可以在catch前就判断

原文地址:https://www.cnblogs.com/liuyouying/p/5074840.html