And*_*ock 8 c# generics reflection
我需要在运行IEnumerable<IEnumerable<T>>时才知道T.
我已经建立了我的收藏品:
new List<List<object>>()
Run Code Online (Sandbox Code Playgroud)
内部列表中的所有对象都是a T
但是,由于CO /逆变的(永远记住它是!)我List的List小号心不是一个IEnumerable的IEnumerable秒.
我该怎么办?
我已经尝试使用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)
简单.在此博客:在内部类型仅在运行时知道时,转换枚举