简体   繁体   中英

Get type of List<T> from object

I have a List of Lists, with each list holding a different class of object. To add elements to the correct list, I need to be able to find the type of the list. I am currently trying to accomplish it in this way:

        foreach(object o in DataBase)
        {
            Type t = o.GetType();
            if (t != typeof(T))
                continue;
            else
            {
                List<T> L = (List<T>)o;
                L.Add(element);
                break;
            }
         }

However, this returns a List Type, of System.Collections.Generic.List`1[[myType,etc,etc]]. Is there a way to extract 'myType' from the type of List, for a proper comparison?

Use GetGenericArguments method:

Type listTypeParam = myListType.GetGenericArguments()[0];

Since myListType is an instance of a generic type with exactly one type parameter, the type T will be returned in the 0-th position of the returned array.

Without explicitly checking the generic argument type, you may be able to refactor the above code as:

foreach(object o in DataBase)
    if (o is List<T>)
    {
        (o as List<T>).Add(element)
        break;
    }

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