Creating an instance from a class name

倾然丶 夕夏残阳落幕 提交于 2020-02-04 01:33:43

问题


I'm trying to create an instance of a class at run time. The classes I'm trying to create all inherit from a base class, ConfigMgrObj, and are named ConfigMgr_xxxxxx e.g. ConfigMgr_Collection. They all take a special object that I'm calling oController and a string as arguments.

This is the line I'm using to do it, where ClassToGet is a string that contains the name of the class e.g. ConfigMgr_Collection.

object oNewObject = System.Activator.CreateInstance(null, "StackOverflowNamespace." + ClassToGet, new object[] { oController, ClassToGet });

This throws a TypeLoadException exception. What's up with it?


回答1:


Are the types you're trying to instantiate actually declared within the same assembly? Passing null as the first parameter is telling Activator that the types live in the current assembly.




回答2:


Looks like it did not find the the class named "StackOverflowNamespace."+ClassToGet in the current assembly.



来源:https://stackoverflow.com/questions/177154/creating-an-instance-from-a-class-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!