1.数字字面量的改进
数字分割符:int million=1_000_000;
二进制使用0b前缀:var b=0b1010_1011
2.输出变量及参数忽略
bool successful=int.TryParse("123",out int result); Console.WriteLine(result)
可以用下划线字符忽略你并不关心的参数:
SomeBigMethod(out _,out_,out int x,out _) Console.WriteLine(x)
3.模式
is运算符可以自然地引入变量,称为模式变量
void Foo(object x) { if(x is string s) Console.WrilteLine(s.Length) }
switch语句同样支持模式,因此我们不仅可以选择常量还可以选择类型;可以使用when子句来指定一个判断条件;或是直接选择null;
switch(x) { case int i: Console.WriteLine("It's an int!"); break; case string s: Console.WriteLine(s.Length); break; case bool b when b==true: Console.WriteLine("True"); break; case null: Console.WriteLine("Nothing"); break; }
4.局部方法
void WriteCubes() { Console.WriteLine(Cube(3)); Console.WriteLine(Cube(4)); Console.WriteLine(Cube(5)); int Cue(int value) => value*value*value; }
5.更多的表达式体成员
public class Person { string name; public Person(string name)=>Name=name; public string Name { get=>name; set=>name=value??""; } ~Person()=>Console.WriteLine("finalize"); }
6.解构器
构造器一般接受一系列值(作为参数)并将其赋值给字段,而解构器则正相反,它将字段反向赋值给变量。以下示例为Person类书写一个解构器(不包含异常处理):
public void Deconstruct(out string firstName,out string lastName) { int spacePos=name.IndexOf(' '); firstName=name.Substring(0,spacePos); lastName=name.Substring(spacePos+1); }
解构器以特定的语法进行调用:
var joe=new Person("Joe Bloggs"); var (first,last)=joe; Console.WriteLine(first); Console.WriteLine(last);
7.元组
显式的元组(tuple)
var bob=("Bob",23); Console.WriteLine(bob.Item1); Console.WriteLine(bob.Item2) //或 var tp=(Name:"Bob",Age:23); Console.WriteLine(tp.Name); Console.WriteLine(tp.Age);
有了元组,就不必通过一系列的out参数来返回多个值了:
static (int row,int column) GetFilePosition()=>(3,10); static void Main() { var pos=GetFilePosition(); Console.WriteLine(pos.row); Console.WriteLine(pos.column); }
元组隐式地支持解构模式。
8. throw表达式
9.null条件运算符
10.表达式体函数
11.属性初始化
也支持只读属性。只读属性可以在构造器中进行赋值。
12.索引初始化器
13.字符串插值(string interploating)
string s=$"It is {DateTime.Now.DayOfWeek} today";
14.异常过滤器(Except filters)
15. using static 指令
16. nameof运算符
17.在catch和finally块中使用await。
18.async和await,asynchronous function,asynchronous continuation,简化响应式和线程安全的富客户端应用程序的编写。它还有利于编写高并发和高效的I/O的密集型应用程序,而不需要为每一个操作绑定一个线程资源。