这是我的属性定义:
[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/