C# - 通过反射枚举自定义属性

标签 c#

这是我的属性定义:

[AttributeUsage(AttributeTargets.Field)]
public class Optional : System.Attribute
{
    public Optional()
    {
    }
}

在我的类(class)中:

[Optional] public TextBox Name;

最后在另一个函数中:

typeof(MyClass).GetFields().ToList<FieldInfo>().ForEach(x => writer.WriteLine(
   x.FieldType + " is called " + 
   x.Name + " and has attributes " + 
   x.GetCustomAttributes(true)[0]
 ));

问题是我收到索引 0 的错误。我只想检查应用该属性的字段。当我删除 x.GetCustomAttributes(true)[0] 时,错误消失了。

确切错误:

异常详细信息:System.IndexOutOfRangeException:索引超出数组范围。

来源错误:

Line 63:             }
Line 64: 
Line 65:             typeof(T).GetFields().ToList<FieldInfo>().ForEach(x => writer.WriteLine(x.FieldType + " is called " + 
Line 66:                 x.Name + " and has attributes " + 
Line 67:                 x.GetCustomAttributes(true)[0]+ "</br>"));

最佳答案

这里似乎有两个问题。要查找具有 [Optional] 属性的所有字段,您需要:

typeof(MyClass).GetFields().Where(
   f => f.GetCustomAttributes(typeof(OptionalAttribute), true).Any())

要在所有字段上写出自定义属性,您需要:

typeof(MyClass).ToList<FieldInfo>().ForEach(x => 
{
 writer.WriteLine(
   x.FieldType + " is called " + 
   x.Name + " and has attributes " + 
   string.Join(", ", x.GetCustomAttributes(true).Select(a => a.ToString()).ToArray()));
});

关于C# - 通过反射枚举自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5125765/

相关文章:

C# linq XML DeepCompare 和标签删除

c# - 如何继续第一个成功的任务,如果所有任务都失败则抛出异常

C# 全局页面变量

c# - 在 C# 中实现基于字符串的日历

c# - Entity Framework 6 w/DatabaseGenerateOption.Compulated : column does not allow nulls. INSERT 失败

c# - JSON 序列化在派生类中缺少属性

c# - MVC Helper,具有相同参数的方法给出不同的结果

c# - Windows 运行时方法不能通用 - 原因、解决方法、替代方案?

c# - 如何使用IList生成数据库?

c# - 如何将脚本语言从 C# 更改为 UnityScript?