2017-06-03 9 views
2

クラスT - GetProperty<Foo>()からプロパティのリストを取得する必要があります。私は次のコードを試しましたが失敗します。C#Reflectionを使用してクラスTからプロパティのリストを取得

サンプルクラス:

public class Foo { 
    public int PropA { get; set; } 
    public string PropB { get; set; } 
} 

は、私は次のコードを試してみました:私は、プロパティ名の一覧を取得する必要があり

public List<string> GetProperty<T>() where T : class { 

    List<string> propList = new List<string>(); 

    // get all public static properties of MyClass type 
    PropertyInfo[] propertyInfos; 
    propertyInfos = typeof(T).GetProperties(BindingFlags.Public | 
                BindingFlags.Static); 
    // sort properties by name 
    Array.Sort(propertyInfos, 
      delegate (PropertyInfo propertyInfo1,PropertyInfo propertyInfo2) { return propertyInfo1.Name.CompareTo(propertyInfo2.Name); }); 

    // write property names 
    foreach (PropertyInfo propertyInfo in propertyInfos) { 
     propList.Add(propertyInfo.Name); 
    } 

    return propList; 
} 

予想される出力:GetProperty<Foo>()

new List<string>() { 
    "PropA", 
    "PropB" 
} 

私はstackoverlowリファレンスをたくさん試しましたが、期待される出力を得ることができません。

参考:

  1. c# getting ALL the properties of an object
  2. How to get the list of properties of a class?

親切に私を助けます。

答えて

5

バインディングフラグが正しくありません。

プロパティは静的プロパティではなくインスタンスプロパティであるため、BindingFlags.StaticBindingFlags.Instanceに置き換える必要があります。

propertyInfos = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); 

これは、タイプのパブリック、インスタンス、非静的プロパティを適切に検索します。この場合、バインディングフラグを完全に省略して同じ結果を得ることもできます。

関連する問題