使用C#反射从类T获取属性列表

B.B*_*dan 3 c# properties system.reflection type-parameter

我需要从类属性的列表T- GetProperty<Foo>().我尝试了以下代码但它失败了.

样品类:

public class Foo {
    public int PropA { get; set; }
    public string PropB { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我尝试了以下代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

我需要获取属性名称列表

预期产量: GetProperty<Foo>()

new List<string>() {
    "PropA",
    "PropB"
}
Run Code Online (Sandbox Code Playgroud)

我尝试了很多stackoverlow引用,但我无法获得预期的输出.

参考:

  1. c#获取对象的所有属性
  2. 如何获取类的属性列表?

请帮助我.

Dav*_*d L 6

您的绑定标志不正确.

由于您的属性不是静态属性,而是实例属性,因此需要替换BindingFlags.StaticBindingFlags.Instance.

propertyInfos = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
Run Code Online (Sandbox Code Playgroud)

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