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

Get List of Properties from a Class T using C# Reflection

我需要从 Class T - GetProperty<Foo>() 中获取属性列表。我尝试了以下代码,但它失败了。

样本Class:

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?

请帮助我。

您的绑定标志不正确。

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

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

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