我需要创建一个 IEnumerable<IEnumerable<T>>
当我只知道T
在运行时。
我是这样建立我的收藏的:
new List<List<object>>()
内部列表中的所有对象都是 T
但是由于协变/逆变(永远记不起它是哪一个!)我的List
的 List
这不是 IEnumerable
的 IEnumerable
我该怎么办?
我试过使用 Convert.ChangeType
但它呻吟着List
不是 IConvertible
线索:阅读问题。再次。我说我只知道T
在运行时。
最佳答案
好的,根据道德大师的回答,我想出了这个。非常简单。
public static IEnumerable Cast(this IEnumerable self, Type innerType)
{
var methodInfo = typeof (Enumerable).GetMethod("Cast");
var genericMethod = methodInfo.MakeGenericMethod(innerType);
return genericMethod.Invoke(null, new [] {self}) as IEnumerable;
}
简单。在这里写博客:Casting an enumerable when the inner type is only known at runtime
关于c# - 如何在 C# 中在运行时转换泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7676989/