标题有点模糊.我想知道的是,如果可能的话:
string typeName = <read type name from somwhere>;
Type myType = Type.GetType(typeName);
MyGenericClass<myType> myGenericClass = new MyGenericClass<myType>();
Run Code Online (Sandbox Code Playgroud)
显然,MyGenericClass被描述为:
public class MyGenericClass<T>
Run Code Online (Sandbox Code Playgroud)
现在,编译器抱怨'找不到类型或命名空间'myType'."必须有办法做到这一点.
假设在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) 这是场景
string dataTypeName = "Employee";
Run Code Online (Sandbox Code Playgroud)
Employee是哪个类,我想创建它的对象.
Type EmployeeObject = Type.GetType(dataTypeName);
Run Code Online (Sandbox Code Playgroud)
现在我想像这样实例化Employee的对象
EmployeeObject emp1 = new Employee();
Run Code Online (Sandbox Code Playgroud)
可能吗.但是这种方法不起作用.我对反思没有强烈的想法.请指导我.
我有一个通用的类
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)
请建议,我该怎么做.