获取类字段列表

本文关键字:列表 字段 获取 | 更新日期: 2023-09-27 18:05:04

我试图为我的搜索创建一个通用方法,但我不知道如何从我的类返回字段列表。

假设我有一个类:

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

现在我想返回一个像这样的列表:

"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) made a difference

获取类字段列表

您可以使用反射:

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

注意,您显然需要属性,而不是字段。术语"字段"指的是私有(实例)成员。公共的getter/setter被称为属性。

您可以编写一个实用程序函数来获取给定类中的属性名称:

static string[] GetPropertyNames<T>() =>
    typeof(T)
        .GetProperties()
        .Select(prop => prop.Name)
        .ToArray();

或者,您可以在Type类上提供一个扩展方法,然后为类型本身配备该特性:

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

您正在寻找使用所谓的反射。您可以通过以下方式获得PropertyInfo对象的数组:

PropertyInfo[] properties = typeof(Table).GetType().GetProperties();
PropertyInfo类包含关于类中每个属性的信息,包括它们的名称(这是您感兴趣的)。你可以用反射做很多很多其他的事情,但这绝对是最常见的一个。

编辑:更改我的答案,不需要Table的实例