1 语法简化
1、主构造函数扩展
允许所有类、结构体和record 类型直接在类型声明中定义主构造函数参数(此前仅 record 支持),
自动生成只读属性,这样可以简化字段和属性的初始化:
// 等效传统构造函数+属性组合 public class Person(string name, int age) { public void PrintInfo() { Console.WriteLine($"{name} is {age} years old."); } }
参数作用域覆盖整个类体,显式构造函数需通过this()
调用主构造函数。
适用于DTO(数据传输对象)设计、不可变类型(如配置类、实体模型)、减少类层级中的样板代码。
2、集合表达式
统一集合初始化语法,支持[]
符号替代传统声明方式:
List<string> names = ["Alice", "Bob"]; // 自动推导为List<string> int[][] matrix = [[1,2], [3,4]]; // 支持多维数组初始化
减少30%样板代码,支持跨数组、列表和Span的无缝转换。
3、默认lamdba参数
Lambda表达式支持可选参数,增强事件处理灵活性:
var add = (int x = 1, int y = 2) => x + y; Console.WriteLine(add()); // 输出 3 var func = (int x = 5) => x * 2; Console.WriteLine(func()); // 输出10
适用于动态生成回调逻辑的场景、简化事件回调和委托设计模式。
2 类型系统优化
1、任意类型别名
通过using
为元组、指针等复杂类型创建别名,不再局限于类型:
using Point = (int X, int Y); Point p = (10, 20); // 等效ValueTuple<int, int> using MyList = System.Collections.Generic.List<int>; MyList numbers = new() { 1, 2, 3 };
2、改进的空值检查
参数级空校验语法!!
自动生成异常:
public void Validate(string s!!) => s.Trim();
编译后自动插入if (s is null) throw new ArgumentNullException(...)
。
3、内联数组
内存紧凑的固定长度数组,优化数值计算场景:
[InlineArray(4)] public struct Vec4 { private float _element0; } // 内存连续存储
性能接近原生数组,减少内存分配开销。
适用优化游戏引擎、数值计算等高性能场景。
3 元编程和AOP改进
1、拦截器
轻量级AOP实现,支持方法调用拦截:
[InterceptsLocation("Program.cs", line: 10)] // 指定拦截位置 public static void LogInterceptor() => Console.WriteLine("Method intercepted!"); [InterceptsLocation("Namespace.Class.Method")] //指定拦截方法 public static void LogInterceptor() => Console.WriteLine("Intercepted!");
ASP.NET Core请求管道已集成这个特性。
2、增强的插值字符串处理
支持自定义插值处理器,优化格式化性能:
var handler = new CustomHandler(); handler.AppendFormatted(value, format); // 自定义格式化逻辑
扩展日志记录等高频字符串操作场景。