如何在运行时在c#中建立一个泛型类型 [英] How to cast a generic type at runtime in c#
问题描述
当我在运行时只知道 T
时,我需要创建一个 IEnumerable< IEnumerable< T>>
我建立了我的集合,如下所示:
new List< ; List< object>>()
内部列表中的所有对象都是 T
然而,由于co / contravariance(永远不会记得它是哪个!)my 我可以做些什么呢? 我试过使用 提示:阅读问题。再次。我说我只知道 在道德大师的回答中,我已经提出了这个问题。令人震惊的简单。 简单。在这里博客:在内部类型仅在运行时才知道的情况下投射一个枚举 I need to create an I have built up my collection like so: where all the objects in the inner list are a However because of co/contravariance (can never remember which it is!) my What can I do about this? I've tried using Clue: Read the question. Again. I said I only know OK, based on Master Morality's answer, I've come up with this. Shockingly simple. Simple. Blogged about it here: Casting an enumerable when the inner type is only known at runtime 这篇关于如何在运行时在c#中建立一个泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! List
List s不是
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);
返回genericMethod.Invoke(null,new [] {self})作为IEnumerable;
}
IEnumerable<IEnumerable<T>>
when I only know T
at runtime.new List<List<object>>()
T
List
of List
s isnt an IEnumerable
of IEnumerable
s.Convert.ChangeType
but it moans that List
isn't IConvertible
T
at runtime.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;
}