为什么System.ComponentModel.AttributeCollection索引器不一致?

本文关键字:不一致 索引 AttributeCollection System ComponentModel 为什么 | 更新日期: 2023-09-27 18:09:38

参考System.ComponentModel.AttributeCollection。这个[Type t]索引器,http://msdn.microsoft.com/en-us/library/yadycs8s.aspx上的文档说如下

如果该属性在集合中不存在,则此属性返回该属性类型的默认值。

考虑到这一点,下面的代码按预期工作:(>表示输出)
using System.ComponentModel;
var attrCollection = new AttributeCollection();
Console.WriteLine(attrCollection[typeof(BrowsableAttribute)] != null);
> "True"

打印"True",正如我所期望的那样。然而,尝试使用另一个随机属性,如DebuggerDisplay,索引器返回null:

var attrCollection = new AttributeCollection();
Console.WriteLine(attrCollection[typeof(System.Diagnostics.DebuggerDisplayAttribute)] != null);
> "False"

这些属性之间有什么不同,导致不同的行为吗?我不清楚msdn的"属性类型的默认值"是什么意思,因为它不是简单的null。我想也许问题是属性类型没有无参数构造函数,但BrowsableAttribute需要一个参数,DebuggerDisplayAttribute也是如此。

为什么System.ComponentModel.AttributeCollection索引器不一致?

在MSDN库文章中明确地记录了AttributeCollection:

虽然大多数属性都有默认值,但默认值不是必需的。如果属性没有默认值,则从采用类型的索引属性返回null。当定义你自己的属性时,你可以通过提供一个不带参数的构造函数,或者定义一个名为" default "的属性类型的公共静态字段来声明一个默认值。

BrowsableAttribute有这样一个默认值,由它的default字段提供,因此您的测试成功。当缺少属性时,它使类成员在默认情况下可浏览。

DebuggerDisplayAttribute既没有默认构造函数,也没有默认字段。这是有道理的,如果你考虑一下,没有有意义的默认值,将在调试器中有用。