C#各版本新功能 C#6.0

只读自动属性

//原来的写法
private int age=100;
public int Age
{
    get { return age; }
}
//现在的写法
public class Person
{
    public int Age { get; } = 100;
}

自动属性初始化器

//以前的写法
public class Person
{
    public int Age { get; set; }

    public Person()
    {
        Age = 100;
    }
}
//现在的写法
public class Person
{
    public int Age { get; set; } = 100;
}

空操作符 ( ?. )

当一个对象或者属性职为空时直接返回null, 就不再继续执行后面的代码,在之前我们的代码里经常出现 NullException, 所以我们就需要加很多Null的判断,比如

//以前的代码
  if (user != null && user.Project != null && user.Project.Tasks != null && user.Project.Tasks.Count > 0)
{
   Console.WriteLine(user.Project.Tasks.First().Name);
}
  string s = null;
  if(s != null)
  {
       Console.WriteLine(s);
  }
//现在的代码可以这样写
string s = null;
Console.WriteLine(s?.Length);

Console.WriteLine(user?.Project?.Tasks?.First()?.Name);

bool hasMore = s?.ToCharArray()?.GetEnumerator()?.MoveNext() ?? false;
Console.WriteLine(hasMore);
//null 条件运算符可以帮助你编写使核心逻辑清晰,同时无缝测试 null 值的代码
  Console.WriteLine(users?[1].Name); // 正常

NameOf

  • 只会返回Member的字符串,如果前面有对象或者命名空间,NameOf只会返回 . 的最后一部分
  • 另外NameOf有很多情况是不支持的,比如方法,关键字,对象的实例以及字符串和表达式
    Console.WriteLine(nameof(System.String));
    int j = 5;
    Console.WriteLine(nameof(j));
    List<string> names = new List<string>();
    Console.WriteLine(nameof(names));
    //String  j   names
  • 另外一个用途,WPF中属性通知 ???
public string LastName
{
    get { return lastName; }
    set
    {
        if (value != lastName)
        {
            lastName = value;
            PropertyChanged?.Invoke(this,
                new PropertyChangedEventArgs(nameof(LastName)));
        }
    }
}
private string lastName;

//以前会存在字符串拼写错误的可能
new PropertyChangedEventArgs(nameof("LastName")));

表达式方法体

  • 简化了方法的写法,不需要再写大括号;
  • 有返回值类型的可以直接写值,不需要return;
  • 不需要返回值void的,可以直接写方法处理的内容;
//原来的写法
public override string ToString()
{
    return FirstName + " " + LastName;
}
//现在的写法
public override string ToString() => FirstName + " " + LastName;

异常筛选器

catch (System.Net.Http.HttpRequestException e) when (e.Message.Contains("301"))
        {
            return "Site Moved";
        }

Catch 和 Finally 块中的 Await

public static async Task<string> MakeRequestAndLogFailures()
{
    await logMethodEntrance();
    var client = new System.Net.Http.HttpClient();
    var streamTask = client.GetStringAsync("https://localHost:10000");
    try {
        var responseText = await streamTask;
        return responseText;
    } catch (System.Net.Http.HttpRequestException e) when (e.Message.Contains("301"))
    {
    //注意里面不要再有异常
        await logError("Recovered from redirect", e);
        return "Site Moved";
    }
    finally
    {
        await logMethodExit();
        client.Dispose();
    }
}
原文地址:https://www.cnblogs.com/maanshancss/p/aa1cb3a3eee1da7f2d90ff2f06dc02ae.html