属性 vs. PropertyInfo中的CustomAttributes

23 浏览
0 Comments

属性 vs. PropertyInfo中的CustomAttributes

我一直在使用Reflections,并且想要获取所有声明的属性的属性。在PropertInfo类下有两个属性,分别是CustomAttributesAttributes

根据MSDN的说明,它们如下所示:

Attributes:

此属性表示与成员相关联的属性。所有成员都有一组与特定类型成员相关的属性。属性属性可以让用户知道此属性是否是默认属性、SpecialName属性等等。

注意:PropertyInfo.Attributes页面上给出的代码示例甚至都不起作用。

自定义属性:

一个包含应用于此成员的所有自定义属性的数组,如果未定义属性,则为零长度数组。

然而,当我对它们运行此代码时,Attributes返回为空,而CustomAttributes返回Required

void Main()
{
    var attributes = typeof(Myproperty).GetProperty("Caption").CustomAttributes;
    //var attributes = typeof(Myproperty).GetProperty("Caption").Attributes;
    attributes.Dump(); //Dump是一个LinqPad方法,将所有内容转储到输出窗口
}
public class Myproperty
{
    private string caption = "Default caption";
    [Required]
    public string Caption
    {
        get{return caption;}
        set {if(caption!=value) {caption = value;}
        }
    }
}

0