【问题标题】:Why is MemberInfo.GetCustomAttributes(Type) defined to return an array of attributes?为什么 MemberInfo.GetCustomAttributes(Type) 被定义为返回一个属性数组?
【发布时间】: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


【解决方案1】:

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

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

如果您想限制您的属性只能使用一次,您可以将allowmultiple:=False 标志添加到您的AttributeUsage

@评论

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

【讨论】:

  • 也就是说,但是哪个父子对具有这些属性?我尝试了一些示例,但在数组中没有得到多个示例。你能设计一个例子来达到这个效果吗?可能是我错过了一些东西。我也会尝试用我的例子来更新这个问题。
  • Alex,太棒了,那个编辑很有道理。它是关于AllowMultiple = True,而不是继承的事情。您能否删除与XmlArrayItemAttribute 和继承相关的部分?还是真的与答案有关?我不这么认为。
  • 现在最大的问题是为什么要定义Attribute.GetCustomAttribute!在我看来,静态函数根本不可靠,而且丑陋:)
  • @nawfal Inheritance 和带有 XmlArrayItemAttribute 的 Constructor 类型只是您想要为每种类型检索多个项目的两个用例。
猜你喜欢
  • 2021-11-10
  • 1970-01-01
  • 2016-09-01
  • 1970-01-01
  • 2018-01-14
  • 2014-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多