简体   繁体   中英

Get strongly typed list item data type?

Lets say I have a List<object> which is passed into a class as an argument, this list should contain a bunch of models for my application all of the same type. Is it then possible for me to somehow retrieve the type of the list which was passed in? (without calling GetType() on a item in the list).

For example, I pass in List<User> which is stored as List<object> , can I now retrieve the type User from the list without doing something like:

List<object> aList;
aList[0].GetType();

Well, you can use:

Type elementType = aList.GetType().GetGenericArguments[0];

However, that will fail if you pass in FooList which derives from List<Foo> for example. You could walk the type hierarchy and work things out appropriately that way, but it would be a pain.

If at all possible, it would be better to use generics throughout your code instead, potentially making existing methods generic - eg instead of:

public void Foo(List<object> list)

you'd have

public void Foo<T>(List<T> list)

or even

public void Foo<T>(IList<T> list)

If you just need it for the very specific case where the execution-time type will always be exactly List<T> for some list, then using GetGenericArguments will work... but it's not terribly nice.

As I understand it, the purpose of generics is to not have to do the type checking manually. The compiler ensures that the items in the list are the type they claim to be, and therefore the items that come out will be that type.

If you have a List<object> , you're defeating the purpose of using generics at all. A List<object> is a list that can store any type of object, no matter what types you actually put into it. Therefore, the onus is upon you to detect what the actual type of the object you retrieve is.

In short: you have to use GetType .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM