繁体   English   中英

C#类型的空列表

[英]C# type of empty list

我可以得到一种非空列表:

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

我如何获得一种空清单?

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

您的代码也适用于空列表。 [0]GetGenericArguments调用返回的类型参数数组的索引器,而不是列表内容。

您拥有的代码有效,例如

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

如果运行时类型没有通用参数(例如,

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

否则它可能无法返回您的期望:

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

也许您应该改用以下方法:

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

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

正如其他人指出的那样,您拥有的代码可以与空集合一起正常工作。 但是,仅当集合类型直接包含泛型变量时,它才起作用。 它不适用于具体的收藏。 例如

class IntList : List<int> { } 

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

IntList类型没有通用参数,因此索引操作[0]将失败。

为了实现更通用的实现,您应该选择一个特定的接口或类类型,以在其中查询通用参数。 我会推荐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