2010-08-05 46 views
5

我调用一个返回对象的函数,在某些情况下,这个对象将是一个List。获取未知类型列表的计数

这个目标可能在的GetType给我:

{System.Collections.Generic.List`1[Class1]} 

{System.Collections.Generic.List`1[Class2]} 

我不关心这个类型是什么,我要的是一个计数。

我已经试过:

Object[] methodArgs=null; 
var method = typeof(Enumerable).GetMethod("Count"); 
int count = (int)method.Invoke(list, methodArgs); 

,但是这给了我,我似乎无法避开不知道类型的AmbiguousMatchException。

我试图铸造的IList但我得到:

无法投类型的对象System.Collections.Generic.List'1 [ClassN]为键入“System.Collections.Generic.IList” 1 [System.Object的]”。

UPDATE

榨渣回答以下实际上是正确的。它不是为我工作的原因是,我有:

using System.Collections.Generic; 

在我的文件的顶部。这意味着我总是使用IList和ICollection的通用版本。如果我指定System.Collections.IList,那么这工作正常。

回答

7

将它转换为ICollection的和使用.Count

List<int> list = new List<int>(Enumerable.Range(0, 100)); 

ICollection collection = list as ICollection; 
if(collection != null) 
{ 
    Console.WriteLine(collection.Count); 
} 
+2

难道我还需要一个类型有关系吗? – 2010-08-05 18:53:11

+0

也许我做错了,但是这给了我错误:使用泛型类型“了System.Collections.Generic.ICollection ”要求“1”类型参数 – 2010-08-05 18:56:39

+0

@克里斯,列表直接实现ICollection的(非通用),它有一个'.Count'属性。不需要类型。为清晰起见添加了示例代码 – Marc 2010-08-05 18:56:42

0

使用的getProperty而不是GetMethod

+0

这将返回一个null – 2010-08-05 18:56:58

3

你能做到这一点

var property = typeof(ICollection).GetProperty("Count"); 
int count = (int)property.GetValue(list, null); 

假设你要通过反射是这样做。

+0

我喜欢这个,但这只有当列表实际上是一个ICollection类型时才起作用。我认为OP的问题并不总是如此。 – Marc 2010-08-05 19:03:23

+0

无可否认,这有点难以分辨,但是既然给出的例子都是'List ',这对于给定的情况是适用的。然而,看看接受的答案,似乎在这种情况下真的没有理由使用反射。如果不需要反射,只需投射到适当的类型就容易得多。 – 2010-08-05 19:08:32

+0

对我不起作用:“使用泛型类型'ICollection '需要1个类型参数” – 2018-03-10 10:37:19

0

你可以做到这一点

var countMethod = typeof(Enumerable).GetMethods().Single(method => method.Name == "Count" && method.IsStatic && method.GetParameters().Length == 1);