2011-01-19 77 views
5

我编写了自定义属性属性并将其设置在我的类中的几个属性上。现在我想在运行时只获取具有此属性的属性,能够获取属性的值以及属性字段的值。你能帮我完成这个任务吗? 感谢您的帮助获取具有值反射的所有属性

+0

我很确定这是一个重复,但还没有找到 比赛。我找到了相关的[Check if property has attribute](http://stackoverflow.com/questions/2051065/check-if-property-has-attribute)和[查找类实例属性的属性] (http://stackoverflow.com/questions/2999035/finding-the-attributes-on-the-properties-of-an-instance-of-a-class)。 – 2011-01-19 15:45:56

回答

13

这里是一个例子:

void Main() 
{ 
    var myC = new C { Abc = "Hello!" }; 
    var t = typeof(C); 
    foreach (var prop in t.GetProperties()) 
    { 
     var attr = prop.GetCustomAttributes(typeof(StringLengthAttribute), true).Cast<StringLengthAttribute>().FirstOrDefault(); 
     if (attr != null) 
     { 
      var attrValue = attr.MaximumLength; // 100 
      var propertyValue = prop.GetValue(myC, null); // "Hello!" 
     } 
    } 
} 
class C 
{ 
    [StringLength(100)] 
    public string Abc {get;set;} 
}