How to get a string name to resolve an object (i.e., in the sense of what it is)

For example, I can do something like:

switch (myString) case "rectangle": o = new rect(); break; case "ellipse" etc... 

but how can I not do the above, i.e. just have one line of code that gets the object directly from the line. Imagine, for example, a button and everything that it says, when the user clicks on it, it displays the text and creates an object from it.

+4
source share
4 answers

If the name is the same as the string, you can do something like this:

 using System; using System.Reflection; class Example { static void Main() { var assemblyName = Assembly.GetExecutingAssembly().FullName; var o = Activator.CreateInstance(assemblyName, "Example").Unwrap(); } } 

A simpler approach would look like this:

 using System; using System.Reflection; class Example { static void Main() { var type = Assembly.GetExecutingAssembly().GetType("Example"); var o = Activator.CreateInstance(type); } } 

But keep in mind that this is a very simple example that does not include namespaces, nodes with strong names, or any other complex things that arise in large projects.

+6
source

He descf,

Have you tried Activator.CreateInstace ("assembly-name", "typename");

+1
source

A Factory pattern will separate code from a string. Please look at this dofactory page for both UML and the C # factory template example.

0
source

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


All Articles