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

C# 检查类字段是否包含指定自定义属性的最优实现方法

最优实现方案

你可以用.NET内置的Attribute.IsDefined()方法优化,该方法仅检查元数据中是否存在目标属性,不需要实例化属性对象,性能和可读性都比你当前的写法更好。

优化后循环写法

foreach (FieldInfo fi in typeof(ClassName).GetFields(BindingFlags.Instance | BindingFlags.NonPublic))
{
    if (Attribute.IsDefined(fi, typeof(AttributeName)))
    {
        Debug.Log($"my GetCustomAttribute check was true for {fi.Name}.");
    }
}

LINQ简化写法

如果需要先批量筛选出所有符合条件的字段,可以用LINQ链式调用:

// 筛选所有标记了目标属性的字段
var matchedFields = typeof(ClassName)
    .GetFields(BindingFlags.Instance | BindingFlags.NonPublic)
    .Where(fi => Attribute.IsDefined(fi, typeof(AttributeName)));

foreach (var field in matchedFields)
{
    Debug.Log($"my GetCustomAttribute check was true for {field.Name}.");
}

特殊场景说明

如果你后续需要读取自定义属性里的配置参数,需要获取属性实例的话,可以用空属性模式匹配简化判空逻辑,不需要额外做类型判断:

foreach (FieldInfo fi in typeof(ClassName).GetFields(BindingFlags.Instance | BindingFlags.NonPublic))
{
    if (fi.GetCustomAttribute<AttributeName>() is {} attribute)
    {
        // 可直接访问attribute的属性/字段取值
        Debug.Log($"字段{fi.Name}的属性参数值为{attribute.自定义参数名}");
    }
}

内容的提问来源于stack exchange,提问作者Nate H.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 23:54:02