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
我猜是不可能的。我想我应该在编写一些反射辅助函数时处理它。
答案 0 :(得分:2)
每个属性类型返回多个项目非常有意义。考虑使用基类设计的属性。或者您可以通过构造函数提供多个选项/类型的属性。
一个例子是XmlArrayItemAttribute
请参阅MSDN:XmlArrayItemAttribute Class
如果您想将属性限制为仅使用一次,则可以将allowmultiple:=False
标记添加到AttributeUsage
。
@comment
DescriptionAttribute
有AllowMultiple:= False(如果你没有指定它,这是默认值 - 至少在VB.NET中)。要获得效果,请创建自己的Attribute
派生属性,并将其标记为AttributeUsage
,并设置AllowMultiple = True
。