c# - 为什么将 MemberInfo.GetCustomAttributes(Type) 定义为返回属性数组?

标签 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

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

最佳答案

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

一个示例是 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/

相关文章:

C# 方法属性

c# - 如何从运行时加载的 DLL 中检索自定义属性的值?

c# - 如何定义 "else" block ?

c# - EntityFramework LINQ 查询计数失败但查询返回结果。如何优化 LINQ 查询?

c# - .Net 开发与 SQLServer 的配对在 ORM 方面有什么优势?

C# JSON 字符串反序列化

.net - 检查 DataReader 中是否存在列,或者不让调试器在某些异常时中断

android - declare-stylable 名称如何链接到使用其属性的 View ?

c# - 在wpf和mvvm中使用后台计算实现用户界面命令

c# - 从大文件中读取 JSON 对象