Getting List Type from a List with a declared type of the superclass
I have three classes (Animal, Mammal, and Reptile) where Mammal and Reptile are subclasses of Animal.
I have a list of Animals that I populate with only Mammals or only Reptiles. I want to get the type inside the list at run-time.
Using the list itself does not work.
Type type = myList.GetType().GetProperty("Item").PropertyType;
// type -> Animal
Type type = myList.GetType().GetGenericArguments()[0];
// type -> Animal
This list is also a property of another class, let's call it Biome. Biome has two 开发者_开发技巧properties, Reptiles (List) and Mammals(List). Given an instance the collection property, can I find the item type?
Get the type of an item in the list, not the type of the list:
Type type = myList[0].GetType();
If you are using .NET 4.0 and know the type of element when you create the list you can apply Generic Covariance as follows:
List<Animal> myList = new List<Reptile>();
That would generate the appropriate output using Reflection.
精彩评论