Instantiate a class from its textual name

后端 未结 2 849
生来不讨喜
生来不讨喜 2020-11-30 05:22

Don\'t ask me why but I need to do the following:

string ClassName = \"SomeClassName\";  
object o = MagicallyCreateInstance(\"SomeClassName\");
相关标签:
2条回答
  • 2020-11-30 06:00
    Activator.CreateInstance(Type.GetType("SomeNamespace.SomeClassName"));
    

    or

    Activator.CreateInstance(null, "SomeNamespace.SomeClassName").Unwrap();
    

    There are also overloads where you can specify constructor arguments.

    0 讨论(0)
  • 2020-11-30 06:16

    Here's what the method may look like:

    private static object MagicallyCreateInstance(string className)
    {
        var assembly = Assembly.GetExecutingAssembly();
    
        var type = assembly.GetTypes()
            .First(t => t.Name == className);
    
        return Activator.CreateInstance(type);
    }
    

    The code above assumes that:

    • you are looking for a class that is in the currently executing assembly (this can be adjusted - just change assembly to whatever you need)
    • there is exactly one class with the name you are looking for in that assembly
    • the class has a default constructor

    Update:

    Here's how to get all the classes that derive from a given class (and are defined in the same assembly):

    private static IEnumerable<Type> GetDerivedTypesFor(Type baseType)
    {
        var assembly = Assembly.GetExecutingAssembly();
    
        return assembly.GetTypes()
            .Where(baseType.IsAssignableFrom)
            .Where(t => baseType != t);
    }
    
    0 讨论(0)
提交回复
热议问题