获取 class 个字段的列表

Getting list of class fields

我正在尝试为我的搜索创建一个通用方法,但我不知道如何从我的 class.

return 字段列表

假设我有一个 class:

public class Table
    {
        [Key]
        public int ID { get; set; }

        public string Name { get; set; }

        public string Address { get; set; }
    }

现在我想要 return 一个如下所示的列表:

"ID"
"Name"
"Address"

我该怎么做?

试过这样的事情:

 FieldInfo[] fields = typeof(T).GetFields(
            BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            string[] names = Array.ConvertAll<FieldInfo, string>(fields,
                delegate(FieldInfo field) { return field.Name; });

但它在字段名称后有一些不必要的文本

编辑

它不是重复的,因为在我的情况下 GetProperties().Select(f => f.Name) 有所不同

你可以用反射来做到这一点:

var listOfFieldNames = typeof(Table).GetProperties().Select(f => f.Name).ToList();

请注意,您显然需要 属性,而不是字段。术语 "fields" 指的是私有(实例)成员。 public getters/setters 称为属性。

您希望使用所谓的反射。您可以通过以下方式获取 PropertyInfo 个对象的数组:

PropertyInfo[] properties = typeof(Table).GetType().GetProperties();

PropertyInfo class 包含有关 class 中每个 属性 的信息,包括他们的名字(这是您感兴趣的)。您可以使用反射做很多很多其他事情,但这绝对是最常见的事情之一。

编辑:将我的答案更改为不需要 Table.

的实例

您可以编写一个实用程序函数来获取给定 class:

中的属性名称
static string[] GetPropertyNames<T>() =>
    typeof(T)
        .GetProperties()
        .Select(prop => prop.Name)
        .ToArray();

或者,您可以在类型 class 上提供扩展方法,然后为类型本身配备该功能:

static class TypeExtensions
{
    public static string[] GetPropertyNames(this Type type) =>
        type
            .GetProperties()
            .Select(prop => prop.Name)
            .ToArray();
}

...

foreach (string prop in typeof(Table).GetPropertyNames())
    Console.WriteLine(prop);

此代码打印 Table 类型的三个 属性 名称:

ID
Name
Address