如何在运行时在c#中转换泛型类型

And*_*ock 8 c# generics reflection

我需要在运行IEnumerable<IEnumerable<T>>时才知道T.

我已经建立了我的收藏品:

new List<List<object>>() 
Run Code Online (Sandbox Code Playgroud)

内部列表中的所有对象都是a T

但是,由于CO /逆变的(永远记住它是!)我ListList小号心不是一个IEnumerableIEnumerable秒.

我该怎么办?

我已经尝试使用Convert.ChangeType,但它的呻吟声是List不是IConvertible

线索:阅读问题.再次.我说我只T在运行时知道.

And*_*ock 16

好的,根据Master Morality的回答,我想出了这个.令人震惊的简单.

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;
}
Run Code Online (Sandbox Code Playgroud)

简单.在此博客:在内部类型仅在运行时知道时,转换枚举

  • 仅供参考,您提到的链接已损坏。 (5认同)