C#6 特性

C#
本文总阅读量:
  1. 1. 字符串拼接
  2. 2. 空操作符 ( ?. )
  3. 3. NameOf
  4. 4. 表达式方法体
  5. 5. 自动属性初始化器
  6. 6. Index 初始化器
  7. 7. using 静态类的方法可以使用 static using

字符串拼接

1
2
var Name = "Jack"; 
var results = $"Hello {Name}"; ## 空操作符

空操作符 ( ?. )

1
2
3
4
5
6
if (user != null && user.Project != null && user.Project.Tasks != null && user.Project.Tasks.Count > 0) 
{
Console.WriteLine(user.Project.Tasks.First().Name);
}
//现在
Console.WriteLine(user?.Project?.Tasks?.First()?.Name);

注意: 上面的代码虽然可以让我们少些很多代码,而且也减少了空异常,但是我们却需要小心使用,因为有的时候我们确实是需要抛出空异常,那么使用这个特性反而隐藏了Bug

NameOf

利用nameof减少手写带来的错误

1
2
3
4
5
Person p;
if(p == null)
{
throw new Exception("nameof(Person)");
}

表达式方法体

1
private static string SayHello() => "Hello World";

自动属性初始化器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//以前
public class Person
{
public int Age { get; set; }

public Person()
{
Age = 100;
}
}
//现在
public class Person
{
public int Age { get; private set; }
}
//同时增加了只读属性初始化
public class Person
{
public int Age { get; } = 100;
}

Index 初始化器

1
2
3
4
5
6
7
var names = new Dictionary<int, string> 
{
[1] = "Jack",
[2] = "Alex",
[3] = "Eric",
[4] = "Jo"
};

using 静态类的方法可以使用 static using

1
2
3
4
5
6
7
8
9
10
11
12
using System; 
using static System.Math;
namespace CSharp6NewFeatures
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Log10(5)+PI);
}
}
}