PropertyInfo中的属性与CustomAttributes

Tar*_*rik 22 .net c# reflection

我一直在使用Reflections,并希望获得为属性声明的所有属性.PropertInfo类下有两个属性是CustomAttributesAttributes.

根据MSDN,他们解释如下:

属性:

此属性表示与成员关联的属性.所有成员都有一组与特定成员类型相关的属性.属性属性允许用户知道此属性是否为默认属性,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 is a LinqPad method which dumps everything to the outpu window
}

public class Myproperty
{
    private string caption = "Default caption";

    [Required]
    public string Caption
    {
        get{return caption;}
        set {if(caption!=value) {caption = value;}
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Han*_*ant 29

PropertyInfo.Attributes与Attribute类没有任何关系.检查PropertyAttributes枚举中可能遇到的值.这些是与C#代码没有明显联系的CLR实现细节.是的,这是一个不幸的命名选择.

要查找[Required]属性等属性,必须使用CustomAttributes属性.