C# string to Class

Use Type.GetType (specifically one of the overloads (e.g., Type.GetType(string)) that takes a string parameter) to load the instance of Type for the appropriate class, and then use Activator.CreateInstance or Type.GetConstructor on that instance of Type to instantiate an instance.

So, something like

Type type = Type.GetType(assemblyQualifiedName);
object instance = Activator.CreateInstance(type);

Note that you must pass the assembly qualified name unless the type is in mscorlib or the currently executing assembly.

Additionally, Activator.CreateInstance assumes the existence of a default constructor. If there is not a default constructor, or you need to pass some parameters to the constructor, you will have to use an overload of Activator.CreateInstance that lets you specify the constructor parameters, or Type.GetConstructor to load the appropriate constructor.

posted on 2020-08-24 17:09  马什么梅  阅读(644)  评论(0编辑  收藏  举报

导航