【发布时间】:2013-06-11 11:21:54
【问题描述】:
public enum Animal
{
[Description("King of jungle")]
Lion= 1,
[Description("Tallest there")]
Giraffe = 2
}
假设我有FieldInfo,我可以通过两种方式进行:
//static one on 'Attribute' class
Attribute attribute = Attribute.GetCustomAttribute(field,
typeof(DescriptionAttribute),
false);
没关系。
但下面的返回 [] 而不是 Attribute ?
//instance one on 'MemberInfo` class
var attributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
这个问题实际上与 MS 的设计选择无关。我的问题是我是否应该担心 field.GetCustomAttributes 返回特定属性类型的多个项目?在什么情况下会发生这种情况?
[Description("King of jungle")]
[Description("I'm a lion")]
Lion= 1
我猜永远不可能。我想我应该在编写一些反射辅助函数时处理它。
【问题讨论】:
-
从同一基本类型派生的多个属性呢?有人可能会查询所有这些?例如 XmlArrayItemAttribute.
-
@Alex 我用这种方式做了一些测试,但数组中仍然只有一个属性。你能举个例子来回答吗?
标签: c# .net custom-attributes fieldinfo getcustomattributes