创建列表<>从运行时类型 [英] Create List<> from runtime type

查看:41
本文介绍了创建列表<>从运行时类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找创建一个List,其中T的类型是我通过反射知道的几个不相关的类(具有相同的构造函数参数).

I am looking to create a List, where the type of T is several unrelated classes (with the same constructor arguments) that I know through reflection.

    DataBase = new ArrayList();
    foreach (Type T in Types)
    {
        DataBase.Add(new List<T>);
    }

不幸的是,Visual Studio说找不到类型或名称空间T".有什么方法可以实现此目的,或者将List强制转换为T类型?谢谢,彼得

Unfortunately, Visual Studio says that 'The type or namespace T could not be found'. Is there some way I can implement this, or cast a List to type T? Thanks, Peter

推荐答案

您可以使用反射:

List<object> database = new List<object>();
foreach (Type t in Types)
{
   var listType = typeof(List<>).MakeGenericType(t);
   database.Add(Activator.CreateInstance(listType));
}

这篇关于创建列表&lt;&gt;从运行时类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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