You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何识别C# record(记录类型)中的主构造函数?

C# Record主构造函数判断方案

完全可以从ConstructorInfo集合中识别出record的主构造函数,常用的有两种可靠方案:

方案1:基于CompilerGenerated特性判断

原理

C#编译器为record隐式生成的主构造函数会自动附加System.Runtime.CompilerServices.CompilerGenerated特性,用户自定义的次级构造函数不会带有该特性。

示例代码

using System.Reflection;
using System.Runtime.CompilerServices;

ConstructorInfo? GetPrimaryConstructorByAttribute(Type recordType)
{
    return recordType.GetConstructors()
        .FirstOrDefault(ctor => ctor.GetCustomAttribute<CompilerGeneratedAttribute>() != null);
}

适用场景

仅适用于没有显式自定义主构造函数实现的常规record,实现简单,判断效率高。

方案2:基于参数与属性匹配判断(通用方案)

原理

record的主构造函数参数列表和声明时定义的位置参数完全对应,参数的名称、类型、顺序和对应位置的公共实例属性1:1匹配,该规则不受是否显式实现主构造函数的影响。

示例代码

using System.Reflection;

ConstructorInfo? GetPrimaryConstructorByPropertyMatch(Type recordType)
{
    PropertyInfo[] publicProperties = recordType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
    
    foreach (var ctor in recordType.GetConstructors())
    {
        ParameterInfo[] ctorParams = ctor.GetParameters();
        if (ctorParams.Length != publicProperties.Length) continue;

        bool isPrimaryCtor = true;
        for (int i = 0; i < ctorParams.Length; i++)
        {
            if (ctorParams[i].Name != publicProperties[i].Name 
                || ctorParams[i].ParameterType != publicProperties[i].PropertyType)
            {
                isPrimaryCtor = false;
                break;
            }
        }

        if (isPrimaryCtor) return ctor;
    }
    return null;
}

适用场景

通用所有record场景,包括显式自定义了主构造函数实现的情况,同时支持record class和record struct。

针对你给出的Foo record示例,两种方案都可以准确识别到Foo(string Text, int Number)为主构造函数。


内容的提问来源于stack exchange,提问作者Matthew Layton

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 08:48:01