获取未知类型列表的计数

Chr*_*son 8 c# generics reflection

我正在调用一个返回一个对象的函数,在某些情况下这个对象将是一个List.

此对象上的GetType可能会给我:

{System.Collections.Generic.List`1[Class1]}
Run Code Online (Sandbox Code Playgroud)

要么

{System.Collections.Generic.List`1[Class2]}
Run Code Online (Sandbox Code Playgroud)

等等

我不在乎这种类型是什么,我想要的只是一个伯爵.

我试过了:

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

但是这给了我一个AmbiguousMatchException,在不知道类型的情况下我似乎无法解决这个问题.

我试过去IList,但我得到:

无法将类型为'System.Collections.Generic.List'1 [ClassN]'的对象强制转换为'System.Collections.Generic.IList'1 [System.Object]'.

UPDATE

Marcs的回答实际上是正确的.它不适合我的原因是我有:

using System.Collections.Generic;
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*arc 10

将其转换为ICollection并使用它 .Count

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

ICollection collection = list as ICollection;
if(collection != null)
{
  Console.WriteLine(collection.Count);
}
Run Code Online (Sandbox Code Playgroud)

  • 如果我指定System.Collections.ICollection或System.Collections.IList - 这实际上现在有效.因为我使用过System.Collections.Generic; 它使用的是这些接口的通用版本.谢谢 (3认同)
  • 我不是还需要一个<T>型? (2认同)
  • 也许我做错了什么,但这给了我:错误 1 ​​Using the generic type 'System.Collections.Generic.ICollection&lt;T&gt;' requires '1' type arguments (2认同)