【发布时间】:2021-03-31 11:50:07
【问题描述】:
我正在调用一个返回对象的函数,在某些情况下,该对象将是一个列表。
此对象上的 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]”。
更新
Marcs 下面的答案实际上是正确的。它对我不起作用的原因是我有:
using System.Collections.Generic;
在我的文件顶部。这意味着我一直在使用 IList 和 ICollection 的通用版本。如果我指定 System.Collections.IList 则可以。
【问题讨论】:
标签: c# generics reflection