使用动态生成的类型创建泛型类的对象

Ish*_*ora 1 c# generics reflection properties class

我有一个通用的类

public  class MyClass<T>
{
   public List<T> Translate(List<T> list, params string[] names)
           {
            //do something here,modify list and return list
       }
    }
Run Code Online (Sandbox Code Playgroud)

现在我可以轻松创建它的实例

MyClass<Employee> obj= new MyClass<Employee>(); OR
MyClass<Vehicle> obj = new MyClass<Vehicle>();
Run Code Online (Sandbox Code Playgroud)

我可以称我的方法为

    obj.Translate(Mylist of employee or vehicle type,"param1","param2")
Run Code Online (Sandbox Code Playgroud)

但在我的情况下,我不知道在运行时生成的类型T,请参阅下面的代码

String classname = string.Empty;

if(Classtype == 1)
{
    classname = "Employee"
}
else if(classtype == 2)
{
    classname = "Vehicle"
}
Run Code Online (Sandbox Code Playgroud)

我想要下面的东西......所以我可以创建这个泛型类的实例

MyClass<typeof(classname)> empp = new MyClass<typeof(classname)>();

    empp.Translate(MyList,"param1","param2")
Run Code Online (Sandbox Code Playgroud)

请建议,我该怎么做.

Moe*_*eri 7

尝试

var someType = Type.GetType("MyProject.Employee");
var yourGenericType = typeof(MyClass<>).MakeGenericType(new [] { someType });
var instance = Activator.CreateInstance(yourGenericType);
Run Code Online (Sandbox Code Playgroud)

请注意,Type.GetType(...)仅适用于类型的完整命名空间,如果您的类与执行此操作的代码不在同一个dll中,则甚至可以使用完整的程序集限定名称.