为什么定义了MemberInfo.GetCustomAttributes(Type)来返回属性数组?

时间:2013-06-11 11:21:55

标签: c# .net custom-attributes fieldinfo getcustomattributes

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

我猜是不可能的。我想我应该在编写一些反射辅助函数时处理它。

1 个答案:

答案 0 :(得分:2)

每个属性类型返回多个项目非常有意义。考虑使用基类设计的属性。或者您可以通过构造函数提供多个选项/类型的属性。

一个例子是XmlArrayItemAttribute请参阅MSDN:XmlArrayItemAttribute Class

如果您想将属性限制为仅使用一次,则可以将allowmultiple:=False标记添加到AttributeUsage

@comment

DescriptionAttribute有AllowMultiple:= False(如果你没有指定它,这是默认值 - 至少在VB.NET中)。要获得效果,请创建自己的Attribute派生属性,并将其标记为AttributeUsage,并设置AllowMultiple = True