2017-06-03 55 views
2

我需要获得类别为T - GetProperty<Foo>()的属性列表。我尝试了下面的代码,但它失败了。使用C#反射获取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.Instance替换BindingFlags.Static

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

这将适当地查找您的类型的公共,实例,非静态属性。您也可以完全省略绑定标志,并在这种情况下获得相同的结果。