Skip to content

C# 14 新特性

更新: 2025-12-08 14:45:00   字数: 0 字   时长: 0 分钟

2025 年 3 月 25 日 C# 14 正式发布

1. 扩展成员

在一个扩展块中同时定义实例与静态扩展方法

c#
public static class StringExtensions
{
    extension(stringvalue)
    {
        public bool IsNullOrEmpty() => string.IsNullOrEmpty(value);
        public string Truncate(int max=> string.IsNullOrEmpty(value)
                || value.Length <= max ? value : value[..max];

        // 静态扩展方法
        public static bool IsAscii(char c=> c <= 0x7F;
    }
}

2. 扩展属性

让模板更干净、意图更清晰:

c#
extension<T>(IEnumerable<T> src)
{
    public bool IsEmpty => !src.Any();
    public int Count => src.Count();
}

3. 扩展块中的私有字段与缓存

在扩展块中也能用私有字段做缓存:

c#
extension<T>(IEnumerable<T> src)
{
    private List<T>? _list;
    public List<T> Materialized => _list ??= src.ToList();
    public bool IsEmpty => Materialized.Count == 0;
}

4. 静态扩展成员

为类型添加静态方法:

c#
extension(Product)
{
    public static Product CreateDefault() => new()
    {
        Name = "Unnamed", Price = 0
    };
    public static bool IsValidPrice(decimal price=> price >= 0;
}

5. 空条件赋值

安全地给可能为 null 的对象赋值:

c#
user?.Profile = LoadProfile();

6. 新增 field 关键字

再也不用手动写 backing field:

c#
public class ConfigReader
{
    public string FilePath
    {
        get => field ??= "data/config.json";
        set => field = value ?? throw new ArgumentNullException(nameof(value));
    }
}

7. Lambda 参数修饰符可省略类型

简化 Lambda 表达式:

c#
delegate bool TryParse<T>(string textout T result);
TryParse<int> parse = (textout result) => int.TryParse(text, out result);

8. 部分类构造函数与事件

方便源生成器使用:

c#
public partial class User
{
    public partial User(string name);
    public partial event Action<string> Saved;
}

9. 自定义复合赋值运算符

自定义 +=、-= 等操作符

c#
public struct Money(string currencydecimal amount)
{
    publicdecimal Amountget; privateset; } = amount;
    publicstring Currencyget; } = currency;

    publicvoidoperator +=(Money b)
    {
        if (Currency != b.Currency) thrownew InvalidOperationException();
        Amount += b.Amount;
    }
}

10. nameof 支持开放泛型 & Span 隐式转换

泛型类型名也能用  nameof,更灵活:

c#
Console.WriteLine(nameof(List<>)); // 输出 "List"
你觉得这篇文章怎么样?
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
评论
  • 按正序
  • 按倒序
  • 按热度