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.
相关产品推荐
相关产品推荐

