String name = "register";
Class<?> classObj = Class.forName(name);
stateComponent = (IState) classObj.newInstance();
这是我在java中创建动态类的代码。任何人都可以给我一个如何在c#中创建动态类的开始?
答案 0 :(得分:3)
与Java的Class<T>
对应的C#类是System.Type
。与Java不同,Type
不是通用的(它不需要,因为.NET不使用类型擦除来实现泛型)。
您的Java代码翻译如下:
string name = "..."; // Full name of your class
Type typeObj = Type.GetType(name);
// Get the default constructor
ConstructorInfo constr = typeObj.GetConstructor(new Type[0]);
// Invoke the constructor to create the object
stateComponent = (IState)constr.Invoke(new object[0]);
答案 1 :(得分:0)
Activator.CreateInstance(Type.GetType("Here your type name"));