C#:在给定对Type的引用的情况下实例化List

Jay*_*Fix 4 c# list

假设在C#中myType是对某些人的引用Type.myType仅使用,是否可以创建一个List对象myType

例如,在下面的代码中,虽然它是错误的,但我想实例化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 > ( ) ;

        }

    }
Run Code Online (Sandbox Code Playgroud)

And*_*ndy 8

你可以使用Reflection做到这一点:

Type typeList = typeof(List<>);
Type actualType = typeList.MakeGenericType(myType);
object obj = Activator.CreateInstance(actualType);
Run Code Online (Sandbox Code Playgroud)