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

标签 c# properties system.reflection type-parameter

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

示例类:

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?

请帮助我。

最佳答案

您的绑定(bind)标志不正确。

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

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

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

关于c# - 使用 C# 反射从类 T 获取属性列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44339870/

相关文章:

c# - 在不创建新实例的情况下反射(reflect)嵌套实例

c# - 子字符串转到字符串结尾

c# - Func<string, bool> 到 bool 用于表达式树

Java 属性与 Android SharedPreferences

Javascript JQuery 属性范围

c#运行时丢失引用

c# - 从枚举类型创建类的最干净的方法?

c# - 显示用户控件而不是文本 MVVM 的组合框

c# - 如何在 XAML 中公开控件以便在其他类中看到

java - 如何识别给定文件或字符串是否为 Java Properties 文件格式?