这里是我的属性定义:C# - 枚举自定义通过反射属性
[AttributeUsage(AttributeTargets.Field)]
public class Optional : System.Attribute
{
public Optional()
{
}
}
在MyClass的:
[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>"));
有什么错误? – harpo 2011-02-26 08:00:34
已添加 - 请记住,如果删除“GetCustomAttributes”部分,则会消失。 – 2011-02-26 08:04:28