更新时间:2023-11-02 18:23:34
将类名放在字符串中并不足以创建其实例.事实上,您需要包含类名的完整命名空间来创建对象.
Having the class name in string is not enough to be able to create its instance. As a matter of fact you will need full namespace including class name to create an object.
假设您有以下内容:
string className = "MyClass";
string namespaceName = "MyNamespace.MyInternalNamespace";
您可以使用以下任一技术创建该类的实例,即 MyNamespace.MyInternalNamespace.MyClass
类的对象:
Than you you can create an instance of that class, the object of class MyNamespace.MyInternalNamespace.MyClass
using either of the following techniques:
var myObj = Activator.CreateInstance(namespaceName, className);
或者这个:
var myObj = Activator.CreateInstance(Type.GetType(namespaceName + "." + className));
希望有帮助,如果没有,请告诉我.
Hope this helps, please let me know if not.