2011-01-19 14 views
5

私はカスタムプロパティ属性を書き、それを私のクラスのいくつかのプロパティに設定しました。今私は実行時に、この属性を持つプロパティだけを取得し、プロパティの値と属性フィールドの値を取得できるようにしたいと思います。あなたはこの仕事で私を助けてくれますか?ヘルプ値の反映を伴うすべてのプロパティを取得

+0

これは重複していますが、一致する。関連する[プロパティに属性があるかどうかを確認する](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)。 –

答えて

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;} 
} 
関連する問題