You need to enable JavaScript to run this app. C# 如何动态读取类属性自定义Attribute 辅助自动SQL生成
优惠活动
大模型
产品
解决方案
定价
更多

C# 如何动态读取类属性自定义Attribute 辅助自动SQL生成

原有实现的核心问题
  • 硬编码单构造参数的匹配规则,只要自定义Attribute的构造函数包含0个、2个及以上参数,逻辑就会直接跳过,完全不具备跨Attribute类型的通用性
  • 拆箱逻辑无类型校验,直接返回构造参数的装箱值,读取时极易出现布尔值类型转换的运行时报错
  • 没有处理AllowMultiple = true的多标记场景,碰到同一属性绑定多个同类型Attribute时,只会返回第一个匹配项的参数值,丢失完整标记信息
  • 没有借助.NET内置的Attribute匹配能力,手动遍历CustomAttributeData的逻辑没有做继承规则适配,比如当前自定义Attribute设置了Inherited = false时,原逻辑的匹配规则会和定义的特性规则不一致
通用动态实现方案

基于.NET反射的原生能力做封装,不需要手动解析构造参数列表、不需要硬编码参数数量,就能适配所有结构的自定义Attribute读取需求:

通用帮助类实现

public static class AttributeHelper
{
    /// <summary>
    /// 读取属性上绑定的指定类型Attribute实例
    /// </summary>
    /// <typeparam name="TAttribute">需读取的自定义Attribute类型</typeparam>
    /// <param name="prop">目标属性的元信息对象</param>
    /// <returns>匹配到的Attribute实例,未匹配返回null</returns>
    public static TAttribute GetCustomAttribute<TAttribute>(PropertyInfo prop) where TAttribute : Attribute
    {
        // 直接调用框架内置的Attribute匹配逻辑,自动适配Inherited规则、多参数构造、属性赋值等所有Attribute结构
        return prop.GetCustomAttributes(typeof(TAttribute), inherit: false)
                   .FirstOrDefault() as TAttribute;
    }

    /// <summary>
    /// 批量遍历类的所有属性,返回属性与对应Attribute的映射关系
    /// </summary>
    public static Dictionary<PropertyInfo, List<TAttribute>> GetAllPropertyAttributes<TAttribute>(Type targetType) where TAttribute : Attribute
    {
        var result = new Dictionary<PropertyInfo, List<TAttribute>>();
        // 仅遍历公共实例属性,跳过静态属性、索引器等不需要做ORM映射的成员
        var properties = targetType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (var prop in properties)
        {
            var matchedAttrs = prop.GetCustomAttributes(typeof(TAttribute), inherit: false)
                                   .Cast<TAttribute>()
                                   .ToList();
            if (matchedAttrs.Any())
            {
                result.Add(prop, matchedAttrs);
            }
        }
        return result;
    }
}

针对自增主键SQL生成场景的使用示例

// 加载Company类所有属性上的Primarykey标记
var propKeyMap = AttributeHelper.GetAllPropertyAttributes<PrimarykeyAttribute>(typeof(Company));
// 筛选出所有标记为true的主键属性
var primaryKeyProps = propKeyMap
    .Where(kv => kv.Value.Any(attr => attr.GetKey()))
    .Select(kv => kv.Key)
    .ToList();
// 过滤得到插入语句需要映射的普通属性(排除自增主键)
var insertMappedProps = typeof(Company)
    .GetProperties(BindingFlags.Public | BindingFlags.Instance)
    .Where(prop => !primaryKeyProps.Contains(prop))
    .ToList();

方案优势

  • 从根源上避免布尔值处理报错:直接返回强类型的Attribute实例,不需要手动对构造参数做拆箱转换,完全规避装箱值类型的转换异常
  • 无结构硬编码:不管自定义Attribute是单参数构造、多参数构造、带属性赋值、带公开方法,都能完整读取实例信息,不需要根据Attribute结构调整代码
  • 自动适配多标记场景:因为自定义Attribute设置了AllowMultiple = true,帮助类直接返回匹配到的所有标记集合,不会遗漏多标记的业务逻辑
  • 自动适配Inherited规则:内置的GetCustomAttributes方法会按照Attribute定义的Inherited标记做匹配,不会出现反射逻辑和特性规则不一致的问题

内容的提问来源于stack exchange,提问作者Tim Verhees

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.28 07:06:01