C#实例从反映类型泛型列表 [英] C# instantiate generic List from reflected Type

查看:192
本文介绍了C#实例从反映类型泛型列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能从在C#反射型(.NET 2.0)创建一个通用对象?

Is it possible to create a generic object from a reflected type in C# (.Net 2.0)?

void foobar(Type t){
    IList<t> newList = new List<t>(); //this doesn't work
    //...
}

本型,T,不知道到运行时。

The Type, t, is not known until runtime.

推荐答案

试试这个:

void foobar(Type t)
{
    var listType = typeof(List<>);
    var constructedListType = listType.MakeGenericType(t);

    var instance = Activator.CreateInstance(constructedListType);
}

现在做什么用实例?因为你不知道你的列表的内容的类型,可能是你能做的最好的事情将是投实例的IList ,这样你可以有不只是一个对象以外的东西:

Now what to do with instance? Since you don't know the type of your list's contents, probably the best thing you could do would be to cast instance as an IList so that you could have something other than just an object:

// Now you have a list - it isn't strongly typed but at least you
// can work with it and use it to some degree.
var instance = (IList)Activator.CreateInstance(constructedListType);

这篇关于C#实例从反映类型泛型列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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