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

查看:48
本文介绍了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);
}

现在如何处理instance?由于您不知道列表内容的类型,因此您能做的最好的事情可能是将 instance 转换为 IList 以便您可以拥有除只是一个 object:

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天全站免登陆