Getting list of class fields

时间:2016-08-31 16:57:09

标签: c# asp.net-mvc generic-programming

I am trying to create a generic method for my search, but I don't know how to return list of fields from my class.

Let's say I've got a class:

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

        public string Name { get; set; }

        public string Address { get; set; }
    }

And now I want to return a list that would look like this:

"ID"
"Name"
"Address"

How do I do that?

tried something like this:

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

But it has some unnecessary text after field names

EDIT

It's not duplicate because in my situation GetProperties().Select(f => f.Name) made a difference

3 个答案:

答案 0 :(得分:5)

You can do this with reflection:

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

Note that you obviously want the properties, not the fields. The term "fields" refers to the private (instance) members. The public getters/setters are called properties.

答案 1 :(得分:1)

You're looking to use what's known as reflection. You can get an array of PropertyInfo objects in the following way:

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

The PropertyInfo class contains information about each property in the class, including their names (which is what' you're interested in). There are many, many other things that you can do with reflection, but this is definitely one of the most common.

EDIT: Changed my answer to not require an instance of Table.

答案 2 :(得分:1)

You could write a utility function which gets names of properties in a given class:

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

Alternatively, you can provide an extension method on the Type class and then equip the type itself with that feature:

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);

This code prints the three property names of the Table type:

ID
Name
Address