2011-01-19 75 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;} 
}