mardi 31 décembre 2019

Getting properties of IEnumerable

I have the following function:

public IEnumerable<string> PropertiesFromType<T>(IEnumerable<T> input)

From the type (T), I would like to get the names of the properties.

I have tried the following:

            var properties = typeof(T).GetProperties();
            //var properties = input.GetType().GetGenericArguments()[0].GetProperties(); // Doesn't work either
            foreach (var item in properties)
            {
                Console.WriteLine(item.Name);
            }

            // By input it does work
            var inputProperties = input.First().GetType().GetProperties();
            foreach (var item in inputProperties)
            {
                Console.WriteLine(item.Name);
            }

When sending an anonymous IEnumerable<object> into the function, it has no properties when retrieving the Type from T.

However, when using the Type of an item in the IEnumerable, it does have properties.

As suggested by: How to get the type of T from a member of a generic class or method? using the GetGenericArguments function neither returns properties.

Example: https://dotnetfiddle.net/Widget/uKzO6H





Aucun commentaire:

Enregistrer un commentaire