简体   繁体   English

C#类型的空列表

[英]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. [0]GetGenericArguments调用返回的类型参数数组的索引器,而不是列表内容。

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). 最大的缺点是您的类型必须实现IEnumerable<T> ,而不仅仅是IEnumerable (但是,如果您想从空列表中获取有用的类型,则必须这样做,否则无论如何都要声明其类型) 。

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. IntList类型没有通用参数,因此索引操作[0]将失败。

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> . 我会推荐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];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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