如何在运行时在c#中建立一个泛型类型 [英] How to cast a generic type at runtime in c#

查看:128
本文介绍了如何在运行时在c#中建立一个泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在运行时只知道 T 时,我需要创建一个 IEnumerable< IEnumerable< T>>



我建立了我的集合,如下所示:

  new List< ; List< object>>()

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



然而,由于co / contravariance(永远不会记得它是哪个!)my 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;
}

简单。在这里博客:在内部类型仅在运行时才知道的情况下投射一个枚举


I need to create an IEnumerable<IEnumerable<T>> when I only know T at runtime.

I have built up my collection like so:

new List<List<object>>() 

where all the objects in the inner list are a T

However because of co/contravariance (can never remember which it is!) my List of Lists isnt an IEnumerable of IEnumerables.

What can I do about this?

I've tried using Convert.ChangeType but it moans that List isn't IConvertible

Clue: Read the question. Again. I said I only know T at runtime.

解决方案

OK, based on Master Morality's answer, I've come up with this. Shockingly simple.

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;
}

Simple. Blogged about it here: Casting an enumerable when the inner type is only known at runtime

这篇关于如何在运行时在c#中建立一个泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆