C# 9有以下更新:
-
模式匹配的增强,包括新的逻辑运算符、新的 is 表达式、新的 switch 表达式等。
-
新的 init-only 属性,使属性只能在初始化时赋值。
-
新的记录类型(record types),可以用于快速创建不可变对象。
-
函数成员可以是顶层语句,无需在类中定义。
-
新的 with 表达式,可用于基于现有记录类型创建新的记录类型。
-
新的 Lambda 表达式的语法,包括更简洁的参数列表和更灵活的类型推断。
-
新的类型推断语法,包括 var 和 target-typed new 表达式。
-
支持异步流(async streams)和异步可枚举(async enumerables)。
在代码中的体现:
- 模式匹配的增强:
-
// 新的逻辑运算符 if (a is 1 or 2) { ... } // 新的 is 表达式 if (obj is string s) { ... }// 新的 switch 表达式 string result = myValue switch {"a" => "A","b" => "B","c" => "C",_ => "unknown" };
- 新的 init-only 属性:
-
public class Person {public string Name { get; init; }public int Age { get; init; } }var person = new Person { Name = "John", Age = 30 }; person.Age = 40; // 编译错误
- 新的记录类型:
-
public record Person(string Name, int Age);var person = new Person("John", 30); var newPerson = person with { Age = 40 };
- 函数成员可以是顶层语句:
-
using System;Console.WriteLine("Hello, world!");
- 新的 with 表达式:
-
var person = new Person("John", 30); var newPerson = person with { Age = 40 };
- 新的 Lambda 表达式的语法:
-
// 更简洁的参数列表 (int x, int y) => x + y// 更灵活的类型推断 (int x, _) => x
- 新的类型推断语法:
-
// var var person = new Person("John", 30);// target-typed new 表达式 Person person = new("John", 30);
- 支持异步流和异步可枚举:
-
async IAsyncEnumerable<int> GenerateNumbersAsync() {for (int i = 0; i < 10; i++){await Task.Delay(100);yield return i;} }await foreach (var number in GenerateNumbersAsync()) {Console.WriteLine(number); }