开发者

Getting List Type from a List with a declared type of the superclass

开发者 https://www.devze.com 2023-03-18 04:36 出处:网络
I have three classes (Animal, Mammal, and Reptile) where Mammal and Reptile are subclasses of Animal.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消