我调用一个返回对象的函数,在某些情况下,这个对象将是一个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,那么这工作正常。
难道我还需要一个类型有关系吗? –
2010-08-05 18:53:11
也许我做错了,但是这给了我错误:使用泛型类型“了System.Collections.Generic.ICollection”要求“1”类型参数 –
2010-08-05 18:56:39
@克里斯,列表直接实现ICollection的(非通用),它有一个'.Count'属性。不需要类型。为清晰起见添加了示例代码 –
Marc
2010-08-05 18:56:42