w wyl123ly 的博客
MD

CSharp-06-现代CSharp特性

65 KB 2026.10.11 原文件

CSharp-06-现代CSharp特性

这篇讲什么

C# 从 2002 年的 1.0 走到今天的 14,主线只有一条:把运行期的错误提前到编译期,把样板代码交给编译器。可空引用类型把 NullReferenceException 提前成警告;模式匹配把一长串 if + 强转 压成声明式的形状描述;Span<T> 让"切片"不再产生堆分配;源生成器把反射搬到编译期。

本篇按"语言演进 → 模式匹配 → 空安全 → 值语义与零分配 → 编译期生成 → 语法糖 → 性能细节"推进。所有示例以 .NET 10 / C# 14 为基准,涉及版本敏感的特性会标注可用版本。

阅读前提:CSharp-01-环境与基础语法、CSharp-02-面向对象(record、接口)、CSharp-03-集合与LINQ(泛型、IEnumerable)。


一、是什么:C# 的语言演进脉络

1.1 各版本关键特性

版本发布关键特性解决的痛点
C# 1.02002类、结构体、接口、委托、事件面向对象的托管语言基线
C# 2.02005泛型、可空值类型 int?、匿名方法、迭代器 yield、分部类类型安全容器、值类型缺省值
C# 3.02007LINQ、Lambda、扩展方法、var、对象初始化器、匿名类型、表达式树查询与数据处理的统一抽象
C# 4.02010dynamic、命名/可选参数、协变与逆变与 COM/动态语言互操作
C# 5.02012async/await、调用方信息特性异步代码的同步写法
C# 6.02015?.、$"" 插值、nameof、表达式体成员、using static、异常筛选器样板代码与空检查
C# 7.x2017–2018元组与解构、out var、模式匹配(首版)、本地函数、ref 返回、Span<T> 配套语法轻量多返回值、取值即判断
C# 8.02019可空引用类型、switch 表达式、using 声明、异步流、默认接口方法、范围 .. 与索引 ^空引用崩溃、冗长分支
C# 9.02020record、init、顶级语句、目标类型 new、模式匹配增强(关系/逻辑/not)、源生成器不可变数据模型、减少缩进
C# 102021文件范围命名空间、global using、记录结构体、Lambda 改进、常量插值字符串每个文件少一层缩进
C# 112022列表模式、原始字符串字面量 """、required 成员、泛型数学、file 作用域类型数组解构匹配、JSON/SQL 字面量
C# 122023主构造函数、集合表达式 [...]、别名任意类型、params 集合、内联数组集合创建与构造样板
C# 132024params 集合增强、\e 转义、ref/unsafe 中的 lock、部分属性与索引器细节打磨
C# 142025扩展成员(extension 块)、field 关键字、空条件赋值、部分构造函数与事件扩展属性/静态成员、属性后备字段

版本与目标框架解耦

语言版本由 <LangVersion> 控制,与目标框架不完全绑定(例如 netstandard2.0 项目也能用 C# 9 的 record,只是部分特性需要额外类型)。

具体可用组合以 配置语言版本 与官方最新文档为准。

1.2 三条演进主线


二、为什么需要这些特性:一个对照实验

同一段"数据校验"逻辑,用 C# 5 风格与 C# 12 风格各写一遍:

// ── 老风格:类型检查 + 强转 + 嵌套 if ──────────────────────────
public static string ValidateOld(object order)
{
    if (order == null) return "订单为空";
    var o = order as Order;
    if (o == null) return "不是订单类型";
    if (o.Status == OrderStatus.Cancelled) return "订单已取消";
    if (o.Items == null || o.Items.Count == 0) return "订单没有明细";
    if (o.Total <= 0) return "金额必须为正";
    if (o.Total > 100000) return "需要人工审核";
    return "通过";
}
// ── 现代风格:模式匹配,形状即逻辑 ─────────────────────────────
public static string Validate(Order? order) => order switch
{
    null                            => "订单为空",
    { Status: OrderStatus.Cancelled } => "订单已取消",
    { Items.Count: 0 }              => "订单没有明细",
    { Total: <= 0 }                 => "金额必须为正",
    { Total: > 100000 }             => "需要人工审核",
    _                               => "通过",
};

差别有三层:没有强转(编译器知道匹配成功后的类型)、没有嵌套(分支平铺,一眼看全)、没有遗漏(配合穷尽性检查,漏掉的情况编译器会提醒)。


三、核心内容

3.1 模式匹配:一张总表

模式语法说明引入版本
类型模式o is Order ord类型检查 + 声明变量C# 7.0
声明模式is string s类型模式的常见形态C# 7.0
常量模式is null、is 42、is "abc"与常量比较C# 7.0 / 9.0 增强
var 模式is var x永远匹配(包括 null)C# 7.0
弃元模式is not null、_不关心值C# 8.0 / 9.0
属性模式{ Length: > 3 }按属性形状匹配C# 8.0
位置模式is (1, 2)调用 Deconstruct 后匹配C# 8.0
元组模式is ( > 0, < 10 )位置的常见用法C# 8.0
关系模式is > 0 and < 100< <= > >=C# 9.0
逻辑模式is not null and not ""and / or / notC# 9.0
圆括号模式is (1 or 2) and not 3改变优先级C# 9.0
列表模式is [1, 2, ..]按序列形状匹配C# 11
切片模式is [1, .. var rest]捕获剩余部分C# 11

模式匹配的两个硬性前提

属性模式要求属性可读;位置模式要求类型有可访问的 Deconstruct 方法(record 会自动生成)。

列表模式要求类型是"可计数的且可索引的":有可访问的 Length 或 Count 属性,且有接受 int 的索引器(Span<T>、数组、List<T> 都满足)。

3.2 类型模式与现代的 is 写法

public abstract class Shape;
public sealed class Circle : Shape { public double Radius { get; init; } }
public sealed class Rect : Shape { public double W { get; init; } public double H { get; init; } }

// 老写法:判断 + 强转(两次类型检查)
static double AreaOld(Shape s)
{
    if (s is Circle)
    {
        var c = (Circle)s;                 // 又一次类型检查
        return Math.PI * c.Radius * c.Radius;
    }
    if (s is Rect)
    {
        var r = (Rect)s;
        return r.W * r.H;
    }
    throw new ArgumentException("未知形状");
}

// 现代写法:类型模式一次完成判断 + 绑定
static double Area(Shape s) => s switch
{
    Circle { Radius: var r } => Math.PI * r * r,
    Rect { W: var w, H: var h } => w * h,
    _ => throw new ArgumentException($"未知形状: {s.GetType().Name}", nameof(s)),
};

// is 模式在 if 中同样好用:匹配成功后的变量在作用域内已是非空的具体类型
static void Describe(Shape s)
{
    if (s is Circle { Radius: > 10 } big)
        Console.WriteLine($"大圆,半径 {big.Radius}");
    else if (s is Rect rect && rect.W == rect.H)
        Console.WriteLine($"正方形,边长 {rect.W}");
    else
        Console.WriteLine("其他形状");
}

is var x 永远为真,包括 null

```csharp

Shape? s = null;

if (s is var x) { Console.WriteLine(x is null); } // 输出 True —— 进了分支但 x 是 null

```

想排除 null 用 is not null 或直接写 is { } x(属性模式匹配任意非空对象)。

3.3 属性模式与关系/逻辑模式

public sealed record Customer(string Name, int Age, string? Email, decimal Balance);

static string Classify(Customer c) => c switch
{
    // 逻辑模式组合多个条件
    { Age: < 18 }                              => "未成年",
    { Age: >= 18 and < 65, Balance: > 1_000_000m } => "高净值客户",
    { Age: >= 18 and < 65 }                    => "普通客户",
    { Age: >= 65 }                             => "老年客户",
    _                                          => "未知",
};

// 嵌套属性模式:直接匹配到内层对象的属性
static bool IsValidContact(Customer c) => c is
{
    Name: not (null or ""),
    Email: { Length: > 3 } e and not null,   // 匹配非空且长度 > 3
};

// 关系模式 + 位运算风格的组合,比一串 && 更易读
static string Grade(int score) => score switch
{
    < 0 or > 100 => "非法分数",
    >= 90        => "A",
    >= 80        => "B",
    >= 70        => "C",
    >= 60        => "D",
    _            => "F",
};

// 用演示数据跑一遍
foreach (var c in new[]
{
    new Customer("小李", 16, "a@b.com", 0m),
    new Customer("王总", 45, "boss@corp.com", 5_000_000m),
    new Customer("张三", 30, null, 100m),
})
{
    Console.WriteLine($"{c.Name}: {Classify(c)}, 联系方式有效={IsValidContact(c)}");
}
Console.WriteLine(Grade(95));   // A
Console.WriteLine(Grade(120));  // 非法分数

为什么关系模式比 when 子句好

case int n when n >= 90: 需要先绑定变量再写卫语句(guard clause),而 >= 90 => ... 把约束直接写在形状里。

两者能力等价,但模式匹配能被编译器做穷尽性分析,when 不能。

3.4 位置模式与解构

位置模式依赖 Deconstruct。record 与 ValueTuple 自带,自定义类型可以手写:

public sealed class Point
{
    public int X { get; }
    public int Y { get; }
    public Point(int x, int y) => (X, Y) = (x, y);

    // 位置模式的入口:out 参数顺序即模式中的位置顺序
    public void Deconstruct(out int x, out int y) => (x, y) = (X, Y);
}

static string Quadrant(Point p) => p switch
{
    (0, 0)                  => "原点",
    ( > 0, > 0)             => "第一象限",
    ( < 0, > 0)             => "第二象限",
    ( < 0, < 0)             => "第三象限",
    ( > 0, < 0)             => "第四象限",
    (0, _) or (_, 0)        => "坐标轴上",
    _                       => "不可能到达",
};

Console.WriteLine(Quadrant(new Point(3, 4)));    // 第一象限
Console.WriteLine(Quadrant(new Point(0, 9)));    // 坐标轴上

// record 的位置模式:参数列表即 Deconstruct 顺序
public sealed record Range(int Low, int High);

static bool Contains(Range r, int value) => r switch
{
    (var lo, var hi) => value >= lo && value <= hi,
};
Console.WriteLine(Contains(new Range(1, 10), 7));   // True

3.5 列表模式

static string Describe(int[] xs) => xs switch
{
    []                      => "空数组",
    [var only]              => $"单元素 {only}",
    [1, 2, ..]              => "以 1,2 开头",
    [.., 9]                 => "以 9 结尾",
    [var first, .., var last] => $"首 {first} 尾 {last},共 {xs.Length} 个",
    _                       => "其他",
};

Console.WriteLine(Describe([]));                  // 空数组
Console.WriteLine(Describe([7]));                 // 单元素 7
Console.WriteLine(Describe([1, 2, 3]));           // 以 1,2 开头
Console.WriteLine(Describe([4, 5, 9]));           // 以 9 结尾
Console.WriteLine(Describe([3, 4, 5]));           // 首 3 尾 5,共 3 个
列表模式要素写法含义
精确长度[1, 2, 3]恰好 3 个元素且值相等
长度下界[_, _, ..]至少 2 个元素
前缀[1, 2, ..]前两个是 1、2
后缀[.., 8, 9]最后两个是 8、9
切片捕获[var a, .. var mid, var z]中间部分绑定为切片(数组/Span)
嵌套[[1, 2], [3, 4]]元素本身也是序列

列表模式的性能特征

编译器把它翻译成 Length/Count 检查 + 索引访问,没有分配;切片捕获会复制出一段新数组(或 Span),这一步有代价。

3.6 switch 表达式的完整用法

using System;

public enum OrderStatus { Created, Paid, Shipped, Delivered, Cancelled, Refunded }

public sealed record OrderLine(string Sku, int Quantity, decimal UnitPrice)
{
    public decimal Amount => Quantity * UnitPrice;
}

public sealed record Order(
    string Id,
    OrderStatus Status,
    decimal Total,
    IReadOnlyList<OrderLine> Items,
    bool IsVip,
    int CustomerAge);

// ── 实战:订单状态机 + 业务规则校验 ─────────────────────────────
public static class OrderRules
{
    // 1) 状态转换是否合法(把状态机写成 switch 表达式,一眼看全)
    public static bool CanTransition(OrderStatus from, OrderStatus to) => (from, to) switch
    {
        (OrderStatus.Created, OrderStatus.Paid)         => true,
        (OrderStatus.Created, OrderStatus.Cancelled)    => true,
        (OrderStatus.Paid, OrderStatus.Shipped)         => true,
        (OrderStatus.Paid, OrderStatus.Refunded)        => true,
        (OrderStatus.Shipped, OrderStatus.Delivered)    => true,
        (OrderStatus.Delivered, OrderStatus.Refunded)   => true,
        (var s, var t) when s == t                      => false,  // 自环禁止
        _                                               => false,  // 其余一律非法
    };

    // 2) 折扣计算:模式匹配天然表达"按客户与订单形状分层定价"
    public static decimal DiscountRate(Order o) => o switch
    {
        { Status: OrderStatus.Cancelled or OrderStatus.Refunded } => 0m,
        { IsVip: true, Total: >= 10_000m }                        => 0.20m,
        { IsVip: true }                                           => 0.10m,
        { Total: >= 5_000m }                                      => 0.05m,
        { CustomerAge: < 25 }                                     => 0.03m,
        _                                                         => 0m,
    };

    // 3) 校验:把"哪里不合格"也一起返回(用元组 + 模式)
    public static (bool Ok, string Reason) Validate(Order o) => o switch
    {
        // 注意顺序:Items.Count == 0 时下面的 Items: [_, ..] 不会匹配,天然互补
        { Items.Count: 0 }                        => (false, "订单没有明细"),
        { Total: <= 0 }                           => (false, "金额必须为正"),
        { Items: [var first, ..] } when first.Quantity <= 0 => (false, "存在非正数量明细"),
        { Status: OrderStatus.Shipped, Total: > 50_000m }   => (false, "大额订单需人工复核后才能发货"),
        _                                         => (true, "OK"),
    };
}

// ── 使用 ────────────────────────────────────────────────────────
var order = new Order(
    Id: "SO-2026-0001",
    Status: OrderStatus.Paid,
    Total: 12_000m,
    Items: new[] { new OrderLine("SKU-1", 2, 6_000m) },
    IsVip: true,
    CustomerAge: 32);

Console.WriteLine($"折扣率: {OrderRules.DiscountRate(order):P0}");                  // 20%
Console.WriteLine($"可发货: {OrderRules.CanTransition(order.Status, OrderStatus.Shipped)}"); // True
Console.WriteLine($"校验: {OrderRules.Validate(order)}");                          // (True, OK)

switch 表达式的四条规则

1. 每个分支是 模式 [when 卫语句] => 表达式,分支之间用 , 分隔。

2. 必须覆盖所有情况,否则编译器报 "并非所有代码路径都返回值"——通常用 _ => ... 或 var x => ... 兜底。

3. 分支自上而下求值,第一个匹配者胜出。所以 < 18 必须写在 < 65 之前(或写成 >= 18 and < 65,更安全)。

4. 元组模式 (a, b) switch 是表达"二维决策表"的最短写法,等价于嵌套 switch 但没有缩进地狱。

3.7 可空引用类型(NRT)

原理:开启 <Nullable>enable</Nullable> 后,编译器对引用类型做流分析(null-state analysis),把每个表达式标记为三种状态之一:

状态含义用法示例
not-null确定非空string s = "a";
maybe-null可能为空string? s = null;
未知未分析到(如来自未标注的程序集)老库的返回值
<!-- .csproj:整个项目启用空安全分析 -->
<PropertyGroup>
  <Nullable>enable</Nullable>
  <TargetFramework>net10.0</TargetFramework>
  <LangVersion>latest</LangVersion>
  <TreatWarningsAsErrors>false</TreatWarningsAsErrors>
</PropertyGroup>
#nullable enable                     // 也可以只对单个文件启用

public sealed class UserService
{
    // string  = 非空引用:调用方不该传 null,返回也不会是 null
    // string? = 可空引用:明确表示"这里可能是 null,请处理"
    public string Greet(string name) => $"你好,{name}";

    public string? FindEmail(int userId) =>
        userId > 0 ? $"user{userId}@example.com" : null;

    public void Demo()
    {
        string? email = FindEmail(0);               // 这里返回的是 null

        // Console.WriteLine(email.Length);         // ⚠ CS8602:可能取消引用 null
        if (email is not null)
            Console.WriteLine(email.Length);        // ✅ 流分析知道这里非空

        Console.WriteLine(email?.Length ?? 0);      // ✅ 条件访问,输出 0

        // ⚠ 下面这样写能过编译,但 email 是 null,运行期照样抛 NullReferenceException
        // Console.WriteLine(email!.Length);
        // 想"安全地"用 ! 必须自己先保证非空,例如:
        string? maybeNull = FindEmail(7);
        Console.WriteLine(maybeNull!.Length);       // ✅ 这个分支下确实是非空("user7@...")

        string? input = Console.ReadLine();
        string safe = input ?? "(空输入)";           // ✅ ?? 提供兜底
        Console.WriteLine(Greet(safe));
    }
}

? 与 ! 的含义必须分清:

写法位置含义
string?类型注解这个引用可能是 null,编译器会盯着你
s!.Something表达式压制警告:"我保证不是 null",不做任何运行期检查
s?.Something表达式条件访问:s 为 null 时整个表达式为 null
s ?? fallback表达式null 合并:为 null 时取备用值
s ??= value表达式null 合并赋值
[NotNullWhen(true)]参数特性告诉分析器"返回 true 时该参数非空"

NRT 是编译期警告,不是运行期保证

```csharp

string s = null!; // 编译通过,运行期 s 就是 null

Console.WriteLine(s.Length); // 运行期照样 NullReferenceException

```

三条必须记住的边界:

1. 反射、序列化、Activator.CreateInstance 会绕过所有检查,构造出字段为 null 的对象。

2. 未标注(nullable-oblivious)的第三方库返回值的状态是"未知",编译器不告警也不保证。

3. 数组元素:new string[10] 的元素是 null,但类型是 string[] 而非 string?[]。分析器对数组元素默认按类型处理,是已知的分析盲区。

在既有项目中渐进启用:

// 策略:先用警告模式统计规模,再逐文件收紧
// 第 1 步(.csproj 全局):只告警不报错,看看有多少
//   <Nullable>warnings</Nullable>
// 第 2 步:新文件用指令强制启用,老文件保持沉默
#nullable enable
// ... 新代码
#nullable restore
渐进策略做法适用
全局 enable一次性全开,修完所有警告新项目、小型项目
全局 warnings全开但只警告中型项目摸底
逐文件 #nullable enable新文件强制,老文件不动大型遗留项目(推荐)
按项目分批从依赖最少的底层项目开始多项目解决方案
注解 vs 警告分开<Nullable>annotations</Nullable> 只加注解不告警类库先提供准确注解

NRT 的常见误用

1. 用 ! 当万能药:满屏 ! 等于关掉了空安全。! 只应在"我比编译器知道得多"的地方出现(如 OnInitialized 之后才赋值的字段)。

2. string? 与 string 混用导致 API 混乱:方法的输入参数通常应该可空(string? name),输出通常不该可空。写反了会让调用方到处判空。

3. 忘了可空字段的初始值:public string Name { get; set; } 会报 CS8618。解法有 required、= string.Empty、或在构造函数中赋值。

4. Equals / GetHashCode 的参数标注不一致:Equals(object? obj) 是正确签名,漏掉 ? 会产生警告。

5. 以为 ?. 之后就安全了:a?.B.C 在 B 为 null 时仍会抛,正确写法是 a?.B?.C。

3.8 元组与解构

// ── ValueTuple(值元组,C# 7+):struct,无堆分配 ──────────────
(int Id, string Name) named = (1, "张三");     // 命名元组
Console.WriteLine($"{named.Id} {named.Name}");

var inferred = (Id: 2, Name: "李四");          // 名字可推断
Console.WriteLine($"{inferred.Id} {inferred.Name}");

(int, string) unnamed = (3, "王五");           // 未命名,用 Item1/Item2
Console.WriteLine($"{unnamed.Item1} {unnamed.Item2}");

// 解构声明与解构赋值
var (id, name) = named;
(id, name) = (9, "赵六");                      // 解构赋值(C# 7.0+)
Console.WriteLine($"{id} {name}");

// 值元组的相等性:按字段逐项比较(ValueTuple 已实现 IEquatable)
Console.WriteLine((1, "a") == (1, "a"));       // True
Console.WriteLine((1, "a").Equals((1, "a")));  // True
// ── Tuple(引用元组,.NET 4.0):class,堆分配,只读 ────────────
Tuple<int, string> legacy = Tuple.Create(1, "张三");
Console.WriteLine($"{legacy.Item1} {legacy.Item2}");
// legacy.Item1 = 2;   // 编译错误:属性是只读的
// Tuple 没有命名元素,也没有 == 运算符重载(只有引用比较!)
对比项ValueTuple((int, string))Tuple<int, string>
类型种类struct(值类型)class(引用类型)
分配无堆分配(字段内联,传递时复制)每次创建都堆分配
可变性字段可读写属性只读
元素名支持命名(Id)只有 Item1/Item2
相等性逐字段值相等(== 与 Equals 都有意义)引用相等(==)
泛型参数上限8 个(第 8 个是 Rest 嵌套)8 个(第 8 个是 TRest)
现状新代码一律用它仅为兼容 .NET 4.0 时代 API
// ── 自定义 Deconstruct:让任意类型支持解构 ──────────────────────
public sealed class GeoPoint
{
    public double Lat { get; }
    public double Lon { get; }
    public double Alt { get; }

    public GeoPoint(double lat, double lon, double alt) => (Lat, Lon, Alt) = (lat, lon, alt);

    // 一个类型可以有多个 Deconstruct 重载,按 out 参数个数区分
    public void Deconstruct(out double lat, out double lon) => (lat, lon) = (Lat, Lon);

    public void Deconstruct(out double lat, out double lon, out double alt)
        => (lat, lon, alt) = (Lat, Lon, Alt);
}

var p = new GeoPoint(39.9042, 116.4074, 43.5);
var (lat, lon) = p;                  // 用两参数版本
var (la, lo, al) = p;                // 用三参数版本
Console.WriteLine($"{lat}, {lon}, 高度 {al}");
Console.WriteLine($"经度在范围内: {(lo is >= -180 and <= 180)}");  // 配合关系模式

元组的适用边界

元组适合方法内部的临时多返回值、以及"这个组合没有独立语义"的场景(如 (bool Ok, string Reason))。

一旦这个组合在多个方法之间传递、或者需要方法/属性,就应该提取为 record——元组没有名字、没有文档、也不能被扩展。

另外不要用元组做公开 API 的长期契约:字段名是编译器元数据,改名不影响二进制兼容性,容易造成隐蔽破坏。

3.9 Span<T> 与 Memory<T>

为什么能避免堆分配:Span<T> 是"指针 + 长度"的引用结构体(ref struct),它只是对一段已存在内存的视图,切片(slice)不复制数据、不创建新数组。

using System;

// ── 对比:字符串切片 vs Span 切片 ──────────────────────────────
string text = "2026-10-11";
string year = text.Substring(0, 4);              // 堆分配一个新 string
Console.WriteLine(year);

ReadOnlySpan<char> span = text.AsSpan();
ReadOnlySpan<char> yearSpan = span.Slice(0, 4);  // 零分配,只是一个视图
Console.WriteLine(yearSpan.ToString());          // 需要 string 时才 ToString()

// 解析日期:整条链路不产生中间字符串
static bool TryParseDate(ReadOnlySpan<char> input, out int y, out int m, out int d)
{
    y = m = d = 0;
    if (input.Length != 10 || input[4] != '-' || input[7] != '-') return false;
    return int.TryParse(input.Slice(0, 4), out y)
        && int.TryParse(input.Slice(5, 2), out m)
        && int.TryParse(input.Slice(8, 2), out d);
}

if (TryParseDate("2026-10-11", out int yy, out int mm, out int dd))
    Console.WriteLine($"{yy}年{mm}月{dd}日");
// ── Span<T> 的常见来源与用法 ───────────────────────────────────
int[] array = { 1, 2, 3, 4, 5 };

Span<int> whole = array;                 // 数组 → Span
Span<int> slice = array.AsSpan(1, 3);    // 视图 {2,3,4}
slice[0] = 99;                           // 写入会改到原数组
Console.WriteLine(string.Join(",", array));   // 1,99,3,4,5

// stackalloc:在栈上分配,方法返回即回收,无 GC 压力
Span<byte> buffer = stackalloc byte[64];
buffer[0] = 0xFF;
Console.WriteLine(buffer[0]);

// 用 Span 做原地变换,避免中间集合
static void ToUpperInPlace(Span<char> chars)
{
    for (int i = 0; i < chars.Length; i++)
        chars[i] = char.ToUpperInvariant(chars[i]);
}

char[] letters = "hello".ToCharArray();
ToUpperInPlace(letters);
Console.WriteLine(new string(letters));  // HELLO
// ── Memory<T>:当 Span 用不了的时候(例如 async 方法里) ────────
public static async System.Threading.Tasks.Task<int> CountAsync(
    Memory<byte> buffer, System.Threading.CancellationToken ct)
{
    // Memory<T> 是普通 struct,可以作为字段、可以跨越 await
    await System.Threading.Tasks.Task.Delay(1, ct);

    // 需要同步操作时,临时取出 Span(只在同步代码块内使用)
    Span<byte> span = buffer.Span;
    int count = 0;
    foreach (byte b in span)
        if (b == 0x0A) count++;          // 统计换行符
    return count;
}

var mem = new byte[] { 1, 10, 2, 10, 3 }.AsMemory(1, 3);   // 视图 {10, 2, 10}
Console.WriteLine(await CountAsync(mem, System.Threading.CancellationToken.None));  // 2
对比项Span<T> / ReadOnlySpan<T>Memory<T> / ReadOnlyMemory<T>
类型种类ref struct(栈上,不能装箱)普通 struct
能否作为类字段不能能
能否用于 async 方法不能能
能否用于迭代器(yield)不能能
能否跨线程传递不能能
切片是否分配否否(Slice 返回新的 Memory<T> 视图)
取元素开销最低(无边界外的额外检查)稍高(需 .Span 再访问)
典型来源数组、stackalloc、string.AsSpan()、Memory.Span数组、ArraySegment<T>、IMemoryOwner<T>
典型场景解析、序列化、字符串处理的热路径异步 IO 缓冲区、需要存字段的缓冲区

ref struct 的限制清单(这也是 Span<T> 的限制)

1. 不能用作泛型类型实参(List<Span<int>> 编译错误)——除非该泛型参数有 allows ref struct 约束(C# 13+)。

2. 不能装箱、不能转成 object、不能作为 dynamic。

3. 不能是类的字段、不能是普通 struct 的字段(除非外层也是 ref struct)。

4. 不能在 async 方法或迭代器方法中跨越 await/yield——因为编译器要把局部变量提升为状态机字段,而 ref struct 不能做字段。这是新手最常撞的墙。

5. 不能实现接口(C# 13 之前)。

编译器的逃生口是 scoped(C# 11)和把 Span 转成 Memory。在 async 方法里需要缓冲区时,用 Memory<T>。

3.10 ref struct 与 stackalloc

// 自定义 ref struct:手写一个只读的字符视图
public readonly ref struct CharWindow
{
    private readonly ReadOnlySpan<char> _source;
    public int Start { get; }

    public CharWindow(ReadOnlySpan<char> source, int start)
    {
        _source = source;
        Start = start;
    }

    public ReadOnlySpan<char> Slice => _source;
    public int Length => _source.Length;
    public override string ToString() => _source.ToString();
}

// 使用:整个过程中只在最后 ToString 时分配了一次
var win = new CharWindow("abcdef".AsSpan(), 1);
Console.WriteLine($"{win} 长度 {win.Length}");     // abcdef 长度 6

// stackalloc 的安全边界:只在同步方法内、且大小可控时使用
public static unsafe string ToHex(ReadOnlySpan<byte> data)
{
    // 栈空间有限(默认 1 MB 栈),大缓冲区仍应用 ArrayPool
    const int StackLimit = 256;
    if (data.Length <= StackLimit)
    {
        Span<char> chars = stackalloc char[data.Length * 2];
        for (int i = 0; i < data.Length; i++)
        {
            data[i].TryFormat(chars.Slice(i * 2, 2), out _, "X2");
        }
        return new string(chars);
    }

    char[] rented = System.Buffers.ArrayPool<char>.Shared.Rent(data.Length * 2);
    try
    {
        var chars = rented.AsSpan(0, data.Length * 2);
        for (int i = 0; i < data.Length; i++)
            data[i].TryFormat(chars.Slice(i * 2, 2), out _, "X2");
        return new string(chars);
    }
    finally
    {
        System.Buffers.ArrayPool<char>.Shared.Return(rented);
    }
}

Console.WriteLine(ToHex(new byte[] { 0xDE, 0xAD, 0xBE, 0xEF }));   // DEADBEEF
Console.WriteLine(ToHex(new byte[100]));                            // 200 个 0

stackalloc 的栈溢出风险

stackalloc byte[n] 中的 n 如果是用户输入,攻击者可以传一个超大值直接把栈撑爆——进程立即崩溃且无法捕获(StackOverflowException 不可 catch)。

规则:栈分配的大小必须由代码常量或严格校验后的上界决定。大缓冲区用 ArrayPool<T>.Shared。

3.11 源生成器

解决什么问题:在编译期生成 C# 代码,把原本运行期用反射做的事情搬到编译期——更快、更可裁剪(AOT 友好)、还能被 IDE 直接看到。

维度运行期反射源生成器
发生时机运行期编译期
性能反射调用有开销生成的是普通代码,与手写等价
裁剪/AOT常被裁剪掉导致运行期失败完全兼容
可调试性只能看反射调用栈生成的文件可在 IDE 里查看与断点
适用完全动态、类型未知类型在编译期已知

所有内置源生成器都需要对应的 using(下列示例已省略项目级的 global using),实际项目中通常放在 GlobalUsings.cs 里。

using System.Text.RegularExpressions;

// ── 例 1:正则源生成器(.NET 7+)────────────────────────────────
// [GeneratedRegex] 要求所在类型是 partial,方法也必须是 partial
public static partial class Validators
{
    // 编译期把正则编译成 IL,运行期零解析成本、零缓存查找
    [GeneratedRegex(@"^\d{4}-\d{2}-\d{2}$", RegexOptions.CultureInvariant)]
    private static partial Regex DateRegex();

    public static bool IsIsoDate(string input) => DateRegex().IsMatch(input);
}

Console.WriteLine(Validators.IsIsoDate("2026-10-11"));   // True
Console.WriteLine(Validators.IsIsoDate("2026/10/11"));   // False
using System.Text.Json;
using System.Text.Json.Serialization;

// ── 例 2:System.Text.Json 源生成(.NET 7+)────────────────────
public sealed record ProductDto(int Id, string Name, decimal Price);

// 为指定类型生成序列化元数据;也可用 JsonSourceGenerationMode 精细控制
[JsonSourceGenerationOptions(
    PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
    WriteIndented = false)]
[JsonSerializable(typeof(ProductDto))]
[JsonSerializable(typeof(List<ProductDto>))]
internal sealed partial class AppJsonContext : JsonSerializerContext;

public static class JsonDemo
{
    public static void Run()
    {
        var dto = new ProductDto(1, "键盘", 399m);

        // 用上下文重载:不再需要运行期反射,AOT 下也能工作
        string json = JsonSerializer.Serialize(dto, AppJsonContext.Default.ProductDto);
        Console.WriteLine(json);                     // {"id":1,"name":"键盘","price":399}

        ProductDto? back = JsonSerializer.Deserialize(json, AppJsonContext.Default.ProductDto);
        Console.WriteLine(back?.Name);               // 键盘
    }
}
内置源生成器特性引入收益
正则[GeneratedRegex].NET 7编译期生成匹配代码,启动更快
JSON 序列化[JsonSerializable] + JsonSerializerContext.NET 7免反射、AOT 兼容、启动更快
日志[LoggerMessage].NET 6免装箱与字符串格式化开销
配置绑定[OptionsValidator].NET 8编译期生成校验逻辑
COM 互操作[GeneratedComInterface].NET 8替代运行期 IL 生成

关于源生成器的三点提醒

1. 必须以官方最新文档为准:源生成器仍在快速演进,具体特性名、包名(如 System.Text.Json 的版本要求)、支持的框架版本请以 官方源生成器文档 为准。

2. 生成的文件默认不显示在解决方案里,需要在 .csproj 中加 <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>,并用 CompilerGeneratedFilesOutputPath 指定输出目录,才能在 IDE 中查看。

3. 调试生成器本身是另一回事:需要单独的 netstandard2.0 分析器项目,用 [Generator] 实现 IIncrementalGenerator。增量生成器(incremental generator)优于旧的 ISourceGenerator,因为它能利用缓存避免重复生成。

3.12 global using 与隐式 using

// ── GlobalUsings.cs:集中声明"全项目可见"的 using ───────────────
global using System;
global using System.Collections.Generic;
global using System.Linq;
global using System.Threading;
global using System.Threading.Tasks;

// 也可以给类型起别名(C# 12 起别名可用于任意类型,包括元组与数组)
global using StrDict = System.Collections.Generic.Dictionary<string, string>;
global using Point = (int X, int Y);
global using Matrix = double[,];
<!-- ── 隐式 using:SDK 按项目类型自动注入一组 global using ────────── -->
<PropertyGroup>
  <!-- 默认 true(自 .NET 6 模板起);关掉它就看不到那些"凭空可用"的命名空间 -->
  <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
  <!-- 也可以手工追加 -->
  <Using Include="System.Text.Json" />
  <Using Include="System.Math" Static="true" />       <!-- 等价于 using static -->
  <Using Include="MyApp.Domain" Alias="Domain" />     <!-- 别名 -->
</ItemGroup>
概念声明位置作用范围典型用途
普通 using.cs 文件顶部单个文件局部依赖
global using任意 .cs 文件整个编译单元(项目)高频命名空间
隐式 using由 SDK 生成整个项目System、System.Linq 等
using static文件或 global按范围静态成员直接使用(如 Math.Sqrt → Sqrt)
using 别名 = 类型文件或 global按范围解决命名冲突、缩短长类型名

实践建议

global using 只放真正处处需要的少数几个命名空间(通常 5–8 个)。

把整个业务命名空间都设成 global 会让"这个类型从哪来"变得难以回答,也容易在重构时产生隐蔽的编译错误。

3.13 文件范围命名空间

// ── 传统块式命名空间:整个文件多一层缩进 ────────────────────────
namespace MyApp.Services
{
    public sealed class OldStyle
    {
        public void Work() { }
    }
}

// ── 文件范围命名空间(C# 10):一个文件只能有一个,且必须在所有成员之前 ──
namespace MyApp.Services;

public sealed class NewStyle
{
    public void Work() { }
}
对比项块式 namespace X { }文件范围 namespace X;
缩进层级多一层无额外缩进
每文件可声明数量多个只能一个
嵌套命名空间namespace A.B { }直接写全名
引入版本C# 1.0C# 10
建议仅在需要一个文件放多个命名空间时使用新代码默认用它

3.14 集合表达式与展开运算符

// ── 集合表达式(C# 12):统一用 [...] 创建各类集合 ───────────────
int[] array = [1, 2, 3];                                     // 数组
List<int> list = [1, 2, 3];                                  // List<T>
Span<int> span = [1, 2, 3];                                  // Span<T>(栈上)
ReadOnlySpan<char> chars = ['a', 'b', 'c'];
IEnumerable<int> enumerable = [1, 2, 3];                     // 编译器选最优实现
HashSet<string> set = ["x", "y"];
Dictionary<int, string> map = new() { [1] = "一", [2] = "二" };  // 字典仍用初始化器

// ── 展开运算符 ..:把另一个集合的内容铺开 ────────────────────────
int[] first = [1, 2, 3];
int[] second = [4, 5];
int[] combined = [.. first, .. second, 6];
Console.WriteLine(string.Join(",", combined));               // 1,2,3,4,5,6

// 展开与切片混合:构造"去掉头尾"的新数组
int[] trimmed = [.. first[1..^1], 99];
Console.WriteLine(string.Join(",", trimmed));                // 2,99

// 空集合与单元素
int[] empty = [];
int[] one = [42];

// 目标类型推断的重要性:var 无法推断集合表达式的类型
// var bad = [1, 2, 3];        // 编译错误 CS9176:没有目标类型
int[] good = [1, 2, 3];
// ── params 集合(C# 13):params 不再局限于数组 ──────────────────
public static int SumAll(params ReadOnlySpan<int> values)
{
    int total = 0;
    foreach (int v in values) total += v;      // 调用时可传数组、Span 或字面量
    return total;
}

Console.WriteLine(SumAll(1, 2, 3));            // 6(无数组分配)
Console.WriteLine(SumAll());                   // 0

集合表达式并不是"新容器"

[1, 2, 3] 只是统一的创建语法,具体类型由目标类型决定(int[] 就是数组,List<int> 就是 List<int>)。

与 new List<int> { 1, 2, 3 } 相比,集合表达式在编译器能算出长度时可以预先分配精确容量,少一次扩容。

更多细节以 集合表达式官方文档 为准。

3.15 required 成员

public sealed class ApiOptions
{
    // required:调用方必须用对象初始化器显式设置,否则编译错误
    public required string BaseUrl { get; init; }
    public required TimeSpan Timeout { get; init; }

    public int RetryCount { get; init; } = 3;      // 有默认值,不必 required

    public void Print() => Console.WriteLine($"{BaseUrl} {Timeout} 重试 {RetryCount}");
}

// ✅ 正确:两个 required 都给了
var ok = new ApiOptions { BaseUrl = "https://api.example.com", Timeout = TimeSpan.FromSeconds(5) };
ok.Print();

// ❌ 下面两种写法都是编译错误 CS9035
// var bad1 = new ApiOptions();
// var bad2 = new ApiOptions { BaseUrl = "https://api.example.com" };
// 与其他初始化方式配合:构造函数的 [SetsRequiredMembers] 表示"我来负责初始化"
public sealed class Config
{
    public required string Name { get; init; }

    [System.Diagnostics.CodeAnalysis.SetsRequiredMembers]
    public Config(string name) => Name = name;
}

var c = new Config("生产环境");     // 构造函数已经赋值,不必再写初始化器
Console.WriteLine(c.Name);
方案表达力何时用
构造函数参数强制,但位置固定、参数多时难读参数少、必填的多
required + 初始化器强制且具名,可读性最好参数多、有可选参数、DTO/Options
可空 + 运行期校验只有运行期保障反序列化边界(配置、JSON)
init 只有可选不可变有默认值的设置项

required 与反序列化的摩擦

很多序列化器需要无参构造,而 required 会让"不设置就编译失败"——这在反序列化路径上是矛盾的。

实践做法:给 DTO 用 required,但为 System.Text.Json 明确标注(.NET 7+ 在 JsonSerializerOptions 中的 RespectRequiredConstructorParameters,或配合源生成器),

或者干脆让 DTO 保持"可空 + 运行期校验"。不要把 required 用在会被反射构造的类型上,除非你确认序列化器支持。

3.16 主构造函数(primary constructor)

// ── 类的主构造函数(C# 12):参数在整个类型体内可见 ──────────────
public sealed class OrderService(IOrderRepository repo, ILogger logger, int retryLimit = 3)
{
    // 参数可直接用于字段初始化器 —— 这里生成一个隐藏的私有字段
    private readonly IOrderRepository _repo = repo;

    // 也可用于方法体:每次使用都会捕获参数(同样产生隐藏字段)
    public async Task<Order?> GetAsync(int id, CancellationToken ct)
    {
        logger.LogInformation("查询订单 {Id}", id);
        for (int attempt = 1; attempt <= retryLimit; attempt++)
        {
            try
            {
                return await _repo.FindAsync(id, ct);
            }
            catch (Exception ex) when (attempt < retryLimit)
            {
                logger.LogWarning(ex, "第 {Attempt} 次失败,重试", attempt);
            }
        }
        return null;
    }
}

// ── 结构体与 record 的主构造函数 ────────────────────────────────
public readonly struct Temp(int celsius)          // 参数被捕获为隐藏字段
{
    public double Fahrenheit => celsius * 9.0 / 5.0 + 32;
    public override string ToString() => $"{celsius}°C = {Fahrenheit:F1}°F";
}

public sealed record Money(decimal Amount, string Currency)   // record 的参数是公开属性
{
    public Money Add(Money other) =>
        Currency == other.Currency
            ? this with { Amount = Amount + other.Amount }
            : throw new InvalidOperationException("币种不同不能相加");
}

Console.WriteLine(new Temp(25));                              // 25°C = 77.0°F
Console.WriteLine(new Money(10m, "CNY").Add(new Money(5m, "CNY")));  // Money { Amount = 15, Currency = CNY }

主构造函数的三个陷阱

1. 参数不是属性(class / struct 场景)。orderService.repo 不存在,外部访问不到;参数只在类型体内可见。

2. 在方法体中使用参数会生成隐藏字段。如果参数只用于字段初始化器,就没有额外字段;一旦方法里用到它,就会多一个私有字段,容易造成意外的对象生命周期延长(例如参数是一个大对象)。

3. 不要用它替代所有构造函数。需要参数校验、需要多个构造重载、或者参数需要 readonly 字段语义时,显式写构造函数更清晰。

3.17 nameof 与调用方信息特性

using System.Runtime.CompilerServices;

public static class Guard
{
    // CallerArgumentExpression(.NET 6+):自动捕获"实参的源码文本"
    public static void NotNull<T>(
        T? value,
        [CallerArgumentExpression(nameof(value))] string? name = null)
        where T : class
    {
        if (value is null)
            throw new ArgumentNullException(name);
    }

    // 组合三个调用方信息特性
    public static void Log(
        string message,
        [CallerMemberName] string member = "",
        [CallerFilePath] string file = "",
        [CallerLineNumber] int line = 0)
    {
        Console.WriteLine($"[{System.IO.Path.GetFileName(file)}:{line} {member}] {message}");
    }
}

public sealed class Reporter
{
    public void Run(string? input)
    {
        Guard.NotNull(input);                  // 异常消息里会是 "input",无需手写字符串
        Console.WriteLine(input!.Length);

        // 三个参数都不用传,调用点只写 message
        Guard.Log("开始处理");
    }
}

new Reporter().Run("abc");

输出形如:[Reporter.cs:12 Run] 开始处理

// nameof 的价值:重构安全 + 编译期校验
public sealed class Person
{
    public string Name { get; set; } = "";
    public int Age { get; set; }

    // 用 nameof 而不是字符串字面量:重命名属性时编译器会一起改
    public void Validate()
    {
        if (string.IsNullOrWhiteSpace(Name))
            throw new ArgumentException("名字不能为空", nameof(Name));

        // nameof 也可以作用于类型、成员、局部变量
        Console.WriteLine(nameof(Person));        // Person
        Console.WriteLine(nameof(Name.Length));   // Length
    }
}
特性捕获内容用途
[CallerMemberName]调用方的成员名INotifyPropertyChanged、日志
[CallerFilePath]调用方源文件路径日志(注意:会暴露构建机路径)
[CallerLineNumber]调用方行号日志、断言
[CallerArgumentExpression]实参的源码文本参数校验、测试断言库

调用方信息会泄露构建环境

[CallerFilePath] 写入的是编译时的绝对路径(如 D:\build\agent\_work\...)。

如果把它们输出到生产日志或嵌入二进制,既泄露构建目录结构,也让构建不可重现(不同机器产出不同字符串)。生产环境慎用。

3.18 性能相关:in 与 ref readonly

using System;

// 大型结构体:按值传递要复制整个结构体
public struct BigStruct
{
    public double A, B, C, D, E, F, G, H;   // 64 字节
    public double Sum() => A + B + C + D + E + F + G + H;
}

public static class Perf
{
    // 按值传递:每次调用复制 64 字节
    public static double SumByValue(BigStruct s) => s.Sum();

    // in 参数:按引用传递,且被调用方**不能修改** —— 零复制 + 只读保证
    public static double SumIn(in BigStruct s) => s.Sum();

    // ref readonly 返回:返回引用(零复制),但调用方也不能写
    private static readonly double[] Table = { 1.0, 2.0, 3.0 };

    public static ref readonly double Lookup(int index) => ref Table[index];
}

var big = new BigStruct { A = 1, B = 2, C = 3, D = 4, E = 5, F = 6, G = 7, H = 8 };
Console.WriteLine(Perf.SumByValue(big));   // 36
Console.WriteLine(Perf.SumIn(big));        // 36 —— 无复制

ref readonly double r = ref Perf.Lookup(1);
Console.WriteLine(r);                      // 2
// r = 99;                                 // 编译错误:ref readonly 不能写入
修饰位置语义何时用
in参数只读引用传递,调用方可省略 in结构体 > 16–24 字节且只需读
ref参数可写引用传递需要被调用方修改调用方变量
out参数输出参数,方法内必须赋值多返回值、TryParse 模式
ref readonly返回值返回引用但不可写暴露大结构体/数组元素而不复制
readonly结构体成员承诺不修改 this消除防御性复制

in 参数会在两种情况下产生防御性复制****

1. 被调用的是非 readonly 的结构体实例方法——编译器必须复制一份以防方法修改 this。

2. 结构体未声明为 readonly struct 且方法未标注 readonly。

结论:in 要与 readonly struct 配套使用,否则可能比按值传递还慢(复制一次 + 引用间接)。判断是否真的更快,请用 BenchmarkDotNet 实测,不要凭直觉。

3.19 特性一览速查

特性版本一句话
类型/属性/位置/关系/逻辑模式7–9用"形状"代替 if + 强转
列表模式11按序列形状匹配,含切片捕获
switch 表达式8分支即表达式,可穷尽检查
可空引用类型8把 NRE 提前成编译期警告
ValueTuple / 解构7轻量多返回值,可与模式配合
Span<T> / Memory<T>7.2 / 2.1 起不断完善零分配切片;前者限于同步
ref struct / stackalloc7.2栈上视图与栈上缓冲
源生成器9把反射工作搬到编译期
global using + 隐式 using10全局命名空间,减少重复
文件范围命名空间10每文件少一层缩进
required 成员11强制调用方初始化
集合表达式 + 展开12统一的 [...] 创建语法
主构造函数12构造函数参数贯穿类型体
nameof / 调用方信息6 / 6 / .NET 6重构安全的名字与源码位置
in / ref readonly7.2大结构体的零复制只读传递

四、常见坑

坑 1:switch 表达式的分支顺序

自上而下匹配,第一个命中者胜出。< 65 写在 < 18 前面会让"未成年"永远匹配不到。

保险写法是把区间写全:>= 18 and < 65。

坑 2:is var x 与 is { } x 的区别

is var x 永远为真(包括 null);is { } x 只在非空时为真。

想"匹配任意非空对象"必须用后者。

坑 3:Span<T> 放进 async 方法

```csharp

// ✗ 编译错误:不能在此上下文中使用 ref struct

// async Task<int> Bad(Span<byte> data) { await Task.Delay(1); return data.Length; }

// ✅ 改用 Memory<T>,或在 await 之后再取 Span

async Task<int> Good(Memory<byte> data) { await Task.Delay(1); return data.Length; }

```

迭代器方法(含 yield)有完全相同的限制。

坑 4:用 ! 掩盖真实的空引用风险

email!.Length 在 email 为 null 时照样抛 NullReferenceException。

! 的正确使用场景极少:OnAfterRenderAsync 之后才赋值的字段、属性注入的依赖、单元测试里的夹具。

坑 5:String.Substring 在热路径上的分配

解析循环中对每一段都 Substring 会产生大量短命字符串,GC 压力显著。

用 AsSpan() + Slice() 改为零分配——但注意不要把 Span 存进字段或跨 await 使用。

坑 6:stackalloc 的大小来自外部输入

用户可控的长度会导致栈溢出(StackOverflowException 无法捕获,进程直接终止)。

一律限制上界,或改用 ArrayPool<T>.Shared。

坑 7:主构造函数参数被误当成属性

```csharp

public sealed class Repo(ILogger logger) { }

// var r = new Repo(logger); r.logger; // ✗ 编译错误:没有这个成员

```

参数只是"类型体内的可见名字",不是公开成员。需要暴露就必须显式写属性。

坑 8:集合表达式没有目标类型

```csharp

// var xs = [1, 2, 3]; // ✗ CS9176:集合表达式没有目标类型

List<int> xs = [1, 2, 3]; // ✅

var ys = new List<int> { 1, 2, 3 }; // ✅

```

坑 9:in 参数配非 readonly 结构体反而更慢

防御性复制会抵消按引用传递的收益。要么把结构体声明为 readonly struct,要么放弃 in。

坑 10:源生成器要求 partial

[GeneratedRegex] 必须放在 partial 类型的 partial 方法上;JsonSerializerContext 派生类型必须是 partial class。

漏了 partial 的报错信息往往不够直白(提示"缺少 partial 修饰符"),第一次遇到容易找不到原因。


五、练习题

练习 1(模式匹配重构)

把下面的代码改写成单个 switch 表达式,要求不出现类型强转和 when 子句。

```csharp

static string Describe(object o)

{

if (o is int) { int n = (int)o; return n > 0 ? "正整数" : (n == 0 ? "零" : "负整数"); }

if (o is string) { string s = (string)o; return s.Length == 0 ? "空串" : "数组({a.Length})"; }

return "未知类型";

}

```

练习 2(列表模式的边界)

写一个方法,判断一个 int[] 是否是"递增序列"(长度 0 或 1 视为递增),要求使用列表模式处理前两个元素的情况,其余用循环或 LINQ 完成。并说明为什么纯列表模式不适合表达"任意长度递增"这种全序列约束。

练习 3(NRT 的取舍)

给定 public string? FindName(int id);,请写出三种调用方处理方式,并说明各自的适用场景。再说明为什么把返回类型改成 public string FindName(int id)(内部返回 string.Empty 而不是 null)有时是更好的 API 设计。

练习 4(Span 与 async)

你需要实现一个方法,从 Stream 读取数据、按行切分、并对每一行做"统计某个字符出现次数"的处理。

请说明哪些部分可以用 Span<char>、哪些必须用 Memory<char> 或 string,并给出方法签名。

练习 5(元组 vs record)

某方法要返回"订单号 + 是否成功 + 错误消息"。请分别用元组和 record 实现,并说明在什么条件下你会从元组迁移到 record。

练习 6(主构造函数)

下面这个类有一个隐藏问题:logger 被用在了方法体里。请说明编译器会生成什么,以及这在什么情况下会导致对象生命周期被意外延长、如何规避。

```csharp

public sealed class Cache(ILogger logger, byte[] bigPayload) { public void Ping() => logger.LogInformation("ping"); }

```

练习 7(源生成器判断)

以下四个场景中,哪些适合用源生成器、哪些更适合运行期反射?请说明理由。

(a) 把任意 object 序列化成 JSON;(b) 对固定的日期格式做正则校验;(c) 根据配置字符串动态调用某个方法;(d) 把 IConfiguration 绑定到强类型 Options 并校验。


六、FAQ

FAQ 1:Nullable 应该设成 enable 还是 annotations?

enable = 注解 + 警告(推荐);annotations = 只加注解、不产生警告。

类库作者在还不能修警告时可以先只开 annotations,这样下游项目能受益于准确的注解;但自己迟早要升到 enable,否则注解容易写错而无人纠正。

disable 与 warnings 是另外两档,前者完全关闭,后者只告警。

FAQ 2:record 和 record struct 怎么选?

record class(默认)是引用类型,相等性按值比较、支持继承、有 with 表达式,适合领域模型。

record struct 是值类型,无堆分配,但默认相等性是逐字段比较(record struct 的 == 也会逐字段比较,与普通 struct 不同),适合小而多的数据载体。

判据:对象是否会被频繁创建在热路径上、是否需要继承、是否需要引用语义。

FAQ 3:Span<T> 真的比 string 快很多吗?

在解析、切分、比较这类高频操作上有量级差异(避免成千上万次短命字符串分配,减少 GC 压力)。

但在"只做一次"的代码上,收益可以忽略,而 ToString() 来回转换的代码可读性更差。

经验法则:热路径 + 大输入 + 高频切片才值得引入 Span<T>;其余情况优先可读性。

FAQ 4:源生成器和 IL 织入(如 Fody、PostSharp)有什么区别?

源生成器在C# 源码层面生成新代码,产物是普通 .cs,能在 IDE 中看到、能被调试、对 AOT 友好。

IL 织入在编译后修改程序集,能力更强(能改已有方法体)但更难调试,且会与裁剪/单文件发布产生摩擦。

能用源生成器解决就不要上 IL 织入。

FAQ 5:global using 会不会影响编译性能或造成冲突?

影响很小(只是把 using 提升到编译单元级别)。真正的风险是可读性与歧义:

两个 global using 的命名空间里有同名类型时,使用处就会报"不明确的引用"。

建议只保留 System 系列与项目内最基础的命名空间。

FAQ 6:in 参数该默认使用吗?

不该。对小于等于指针大小 × 2(约 16 字节)的结构体,按值传递通常更快(寄存器传递、无间接寻址)。

只对较大的 readonly struct 才考虑 in,且必须用基准测试验证;否则会引入不必要的复杂度。

FAQ 7:C# 14 的 field 关键字与 extension 块值得用吗?

field(C# 14)让属性可以引用编译器生成的后备字段,省掉手写 _name 字段——语义清晰、减少样板。

extension 块(C# 14)让扩展方法、扩展属性、甚至静态扩展成员集中在一个块里声明,比散落的 static 扩展方法更易组织。

二者都是新特性,具体语法与可用框架版本请以官方最新文档为准,团队引入前应确认 SDK 与工具链支持情况。


七、小结

你的目标该用的特性
消除 if + 强转类型/属性/位置/关系/逻辑模式 + switch 表达式
编译期防住空引用可空引用类型 + required + ??/?.
方法返回多个值ValueTuple + 解构(稳定契约则用 record)
热路径消除分配Span<T> + stackalloc + ArrayPool<T>
异步中处理缓冲区Memory<T>(Span<T> 不能跨 await)
避免运行期反射源生成器(正则、JSON、日志、配置)
减少样板global using、文件范围命名空间、集合表达式、主构造函数
让调用方信息自动到位nameof + [CallerArgumentExpression] 等
大结构体零复制in + readonly struct + ref readonly

最后一条建议

语言特性是工具,不是目标。引入新特性前问自己两个问题:

1. 它是否让错误更早暴露(模式匹配的穷尽性、NRT 的警告)?

2. 它是否让意图更直接(集合表达式、主构造函数)?

两条都不满足的"炫技式写法",应该果断放弃。


相关笔记

  • CSharp-02-面向对象 —— record、init、接口与多态:模式匹配与空安全的基础
  • CSharp-03-集合与LINQ —— 集合表达式、IEnumerable、延迟执行与模式匹配在查询中的配合
  • CSharp-05-异步编程 —— 为什么 Span<T> 不能跨越 await、ValueTask 的零分配思路
  • CSharp-07-dotnet项目与工具链 —— LangVersion、Nullable、源生成器相关的项目配置
  • 后端-03-ASPNET-Core —— Options 模式、required 成员与源生成器在实际后端的落地

参考来源