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
请参阅 MSDN:XmlArrayItemAttribute Class
如果您想限制您的属性只使用一次,您可以将 allowmultiple:=False
标志添加到您的 AttributeUsage
。
@评论
DescriptionAttribute
具有 AllowMultiple:=False(如果您不指定它,这是默认值 - 至少在 VB.NET 中)。要获得效果,请创建您自己的派生自 Attribute
的属性,并在设置 AllowMultiple = True
的地方用 AttributeUsage
标记它。
关于c# - 为什么将 MemberInfo.GetCustomAttributes(Type) 定义为返回属性数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17042867/