属性 vs. PropertyInfo中的CustomAttributes
属性 vs. PropertyInfo中的CustomAttributes
我一直在使用Reflections,并且想要获取所有声明的属性的属性。在PropertInfo
类下有两个属性,分别是CustomAttributes
和Attributes
。
根据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;} } } }