简体   繁体   中英

How to get a string name to resolve to 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 do I not do the above, ie just have one line of code that gets the object directly from the string. Imagine, for example, a button and whatever it says when the user clicks it, it takes the displayed text and creates an object from it.

If the name is the exact same thing 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 doesn't involve namespaces, strong-named assemblies, or any other complicated things that crop up in bigger projects.

He descf,

Have you tried Activator.CreateInstace("assemblyname", "typename");

A Factory pattern would decouple the code from the string. Please take a look at this dofactory page for both the UML and a C# example of the Factory pattern.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM