简体   繁体   中英

C# type of empty list

I can get a type of non empty list:

private Type GetListType(IEnumerable list)
{
  return list.GetType().GetGenericArguments()[0];
}

How i can get a type of empty list?

private Type GetListType(IEnumerable list)
{
...
}

Your code works for empty lists too. The [0] is an indexer over the array of type arguments returned by the GetGenericArguments call, not your list's contents.

The code you have works, eg in

GetListType(new List<string>()); // typeof(string)

It will not work if the runtime type doesn't have a generic parameter, eg

public class MyList : List<SomeObject> { }
GetListType(new MyList()); // there is no 0'th generic argument!

Or it might not return what you're expecting:

GetListType(new Dictionary<string, int>()); // typeof(string)
// even though it ought to be KeyValuePair<string, int>

Maybe you should use this instead:

private Type GetListType<T>(IEnumerable<T> list)
{
  return typeof(T);
}

The biggest downside of this is that your type must implement IEnumerable<T> , not just IEnumerable (but if you wanted to get a useful type from an empty list, it'd have to do this, or otherwise declare its type, anyway).

As others have pointed out the code you have will work fine with an empty collection. But it will only work when the collection type directly contains a generic variable. It will not work for concrete collections. For example

class IntList : List<int> { } 

GetListType(new List<int>()) // Works
GetListType(new IntList())   // Fails

The type IntList has no generic parameters hence the index operation [0] will fail.

To make a more general purpose implementation you should pick a particular interface or class type in which to query for the generic parameter. I would recommend IEnumerable<T> .

static Type GetListType(IEnumerable enumerable)
{
    var type = enumerable.GetType();
    var enumerableType = type
        .GetInterfaces()
        .Where(x => x.GetGenericTypeDefinition() == typeof(IEnumerable<>))
        .First();
    return enumerableType.GetGenericArguments()[0];
}

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