2017-03-24 5 views
1

プロパティと、必須属性を持つクラス内のすべてのプロパティのDisplayNameを含む辞書を取得しようとしています。クラス内のすべての必須プロパティのリストを返します

私はこの拡張メソッドを使いこなそうとしていますが、PropertyDescriptorにはRequiredの定義が含まれていません。任意の方向が

public static Dictionary<string, string> GetDisplayNameList<T>() 
    { 
     var info = TypeDescriptor.GetProperties(typeof(T)) 
      .Cast<PropertyDescriptor>() 
      .ToDictionary(p => p.Name, p => p.DisplayName); 
     return info; 
    } 

答えて

1

確かに高く評価されるだろう、あなただけのプロパティがそれに定義されたRequired属性を持っていることを確認する必要があります。これは.Attributesでアクセスできます。例:

public static Dictionary<string, string> GetDisplayNameList<T>() 
{ 
    var info = TypeDescriptor.GetProperties(typeof(T)) 
     .Cast<PropertyDescriptor>() 
     .Where(p => p.Attributes.Cast<Attribute>().Any(a => a.GetType() == typeof(RequiredAttribute))) 
     .ToDictionary(p => p.Name, p => p.DisplayName); 
    return info; 
} 
+1

おかげでロブ。それがまさに私が必要としていたものです。 – Tim

+1

個人的には、私は['.Where(p => p.GetCustomAttribute ()!= null)'](https://msdn.microsoft.com/en-us/library/hh194292(v=vs.110) ).aspx)たくさんのクリーナー。 –

+0

@ScottChamberlain私は通常これを使用しますが、残念なことにこれは 'PropertyInfo'ではなく' PropertyDescriptor'にあります – Rob

0

これは機能しませんか?私は離れて自分のコンピュータからだと私はDisplayNameについてここで少しを推測している

public static Dictionary<string, string> GetNameToDisplayNameDictionary(List<T>() list) => 
    typeof(T) 
     .GetProperties() 
     .Where(p => p.GetAttribute<RequiredAttribute>() != null) 
     .ToDictionary(p => p.Name, p => p.GetAttribute<DisplayName>().Name); 

...

関連する問題