我有一个通用类
public class MyClass<T>
{
public List<T> Translate(List<T> list, params string[] names)
{
//do something here,modify list and return list
}
}
现在我可以很容易地创建它的实例了
MyClass<Employee> obj= new MyClass<Employee>(); OR
MyClass<Vehicle> obj = new MyClass<Vehicle>();
我可以像这样调用我的方法
obj.Translate(Mylist of employee or vehicle type,"param1","param2")
但在我的例子中,我不知道运行时生成的类型 T,请参见下面的代码
String classname = string.Empty;
if(Classtype == 1)
{
classname = "Employee"
}
else if(classtype == 2)
{
classname = "Vehicle"
}
我想要下面这样的东西..这样我就可以创建这个通用类的实例
MyClass<typeof(classname)> empp = new MyClass<typeof(classname)>();
empp.Translate(MyList,"param1","param2")
请建议,我该怎么做。
最佳答案
尝试
var someType = Type.GetType("MyProject.Employee");
var yourGenericType = typeof(MyClass<>).MakeGenericType(new [] { someType });
var instance = Activator.CreateInstance(yourGenericType);
请注意,Type.GetType(...) 仅适用于类型的完整命名空间,如果您的类与执行此代码的代码不在同一个 dll 中,则甚至可以使用完整的程序集限定名称。
关于c# - 使用动态生成的类型创建通用类的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20076478/