mardi 28 juin 2016

Obtain Properties in Child Classes in IEnumerable of Base Class

If I have an collection of a given entity, I'm able to obtain the properties for entity like so:

var myCollection = new List<Foo>(); 
entities.GetType().GetGenericArguments()[0].GetProperties().Dump();

However, I'm having some difficulties listing out the properties if my collection is an IEnumerable of a base class and populated with derived classes.

public class Foo
{
    public string One {get;set;}
}

public class Bar : Foo
{
    public string Hello {get;set;}
    public string World {get;set;}
}

// "Hello", "World", and "One" contained in the PropertyInfo[] collection
var barCollection = new List<Bar>() { new Bar() };
barCollection.GetType().GetGenericArguments()[0].GetProperties().Dump();

// Only "One" exists in the PropertyInfo[] collection
var fooCollection = new List<Foo>() { new Bar() };
fooCollection.GetType().GetGenericArguments()[0].GetProperties().Dump();

Is there anyway to get the types of the items in the collection even though the collection is declared using the base class?





Aucun commentaire:

Enregistrer un commentaire