You need to enable JavaScript to run this app. 如何在运行时校验.NET 5中C#9 Record的不可变性或检测init属性
优惠活动
大模型
产品
解决方案
定价
更多

如何在运行时校验.NET 5中C#9 Record的不可变性或检测init属性

运行时检测C# 9 Record不可变性与Init属性实现

Record是C# 9、.NET 5推出的全新特性,微软官方文档明确说明:

如果需要对象整体不可变且具备值语义,建议优先将其声明为record类型。

在C# 9、.NET 5环境下,可通过如下方式创建record:

public record Rectangle
{
    public int Width { get; init; }
    public int Height { get; init; }
}

对应的实例化写法为:

var rectangle = new Rectangle(20, 30);

尝试在实例初始化完成后修改属性时,会触发编译器错误:

rectange.Width=50; // 编译报错

编译器抛出的错误信息为:error CS8852: Init-only property or indexer 'Rectangle.Width' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. 这类编译限制确实能保障record的不可变性。

但使用通用的类型不可变性检测逻辑时,对上述record的检测结果往往为false,核心原因是record默认不会生成带readonly修饰的属性,和传统不可变类型的运行时特征存在差异。针对如何在运行时检测C# 9 Record的不可变性、识别init属性的问题,可通过以下逻辑实现:

核心检测方法

识别init-only属性

init修饰的属性,本质是编译器在属性的set访问器上添加了System.Runtime.CompilerServices.IsExternalInit的必要修改符(modreq),运行时可通过检查set访问器的自定义修改列表识别:

public static bool IsInitOnlyProperty(PropertyInfo property)
{
    // 无set访问器的纯只读属性直接返回false
    var setMethod = property.SetMethod;
    if (setMethod == null) return false;
    // 检查set方法是否标记了IsExternalInit必要修改符
    return setMethod.ReturnParameter
        .GetRequiredCustomModifiers()
        .Any(mod => mod.FullName == "System.Runtime.CompilerServices.IsExternalInit");
}

判断Record整体是否不可变

结合C# 9 Record的运行时特征,只要满足以下两个条件,即可判定为整体不可变类型:

  • 所有非静态公开属性,要么是无set访问器的纯只读属性,要么是init-only修饰的属性,不存在公开的普通可写set访问器
  • 所有非静态公开字段,均为readonly修饰

对应实现逻辑如下:

public static bool IsImmutableRecord(Type type)
{
    // 判断目标类型是否为record
    // Record的运行时特征为存在受保护的get-only EqualityContract属性,用于值相等比较
    var isRecord = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance)
        .Any(prop => prop.Name == "EqualityContract" && prop.GetMethod != null && !prop.CanWrite);
    if (!isRecord) return false;

    // 遍历检查所有公开实例属性
    var publicProperties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
    foreach (var prop in publicProperties)
    {
        // 跳过record值语义自带的EqualityContract属性
        if (prop.Name == "EqualityContract") continue;
        // 存在普通可写set(非init、非只读)则判定为可变
        if (prop.CanWrite && !IsInitOnlyProperty(prop))
        {
            return false;
        }
    }

    // 遍历检查所有公开实例字段
    var publicFields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
    foreach (var field in publicFields)
    {
        if (!field.IsInitOnly) return false;
    }

    return true;
}

补充说明

常规不可变类型检测逻辑之所以识别不出这类record,是因为之前的判断逻辑仅识别带readonly修饰的get-only属性,没有覆盖C# 9引入的init访问器特征,只要补充上述init属性的判断分支,就能和编译期的不可变约束形成匹配。


内容的提问来源于stack exchange,提问作者M.Hassan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.26 15:15:03