Creating a .Net Object by Class Name

I have an abstract Step class and many Step stream classes that I would like to create from an XML document.

As such, I would like to instantiate a specific class of steps based on the type in the XML document

Step Type = "GenerateReport" .... Step Type = "PrintReport" ....

How can I instantiate an object by specifying the class name (and, ideally, the parameters passed to the constructor)?

+4
source share
2 answers

The easiest option is to overload Activator.CreateInstance , which takes Type and a params object[] . For Type you can sometimes use Type.GetType(string) , but this does not check all assemblies (only the current assembly and some system assemblies). If the name meets the requirements of the assembly, you'll probably be fine, but if it's just the namespace name (i.e. FullName), then you probably want to use Assembly.GetType(string) - i.e.

 Type type = typeof(SomeKnownTypeInTheSameAssembly).GetType(fullName); object obj = Activator.CreateInstance(type, args); 
+5
source

I think you just want to use the Activator.CreateInstance method:

 var object = Activator.CreateInstance(null, "Classname"); 
+6
source

Source: https://habr.com/ru/post/1285635/


All Articles