C#:实例化一个列表,给一个类型的引用 [英] C# : instantiate a List, given a reference to a Type

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

问题描述

假设在C#中,的myType 在一定键入的参考。
使用的myType 而已,是有可能创造的对象列表的myType



例如,在下面的代码,虽然它是错误的,我想通过

$ b实例
$ b

新的List < 的myType > ()

 使用系统; 
使用的System.Reflection;
使用System.Collections.Generic;

类MyClass的
{
}

类MainClass
{

公共静态无效的主要(字符串[ ]参数)
{

型=的myType typeof运算(MyClass的);

名单,LT; &的myType GT; myList中=新名单,LT; &的myType GT; ();

}

}


解决方案

您可以这样做,使用反射:

 键入TYPELIST = typeof运算(名单<>); 
型actualType = typeList.MakeGenericType(的myType);
obj对象= Activator.CreateInstance(actualType);


Suppose that, in C#, myType is a reference to some Type. Using myType only, is it possible to create a List of objects of myType ?

For example, in the code below, although it is erroneous, I'd like to instantiate via

new List <myType> ( ) .

using System ;
using System.Reflection ;
using System.Collections.Generic ;

class MyClass
    {
    }

class MainClass
    {

    public static void Main ( string [] args )
    	{

    	Type  myType  =  typeof ( MyClass ) ;

    	List < myType >  myList  =  new List < myType > ( ) ;

    	}

    }

解决方案

You can do so using Reflection:

Type typeList = typeof(List<>);
Type actualType = typeList.MakeGenericType(myType);
object obj = Activator.CreateInstance(actualType);

这篇关于C#:实例化一个列表,给一个类型的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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