Instantiate a class from its textual name

旧街凉风 提交于 2019-12-28 02:04:59

问题


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

string ClassName = "SomeClassName";  
object o = MagicallyCreateInstance("SomeClassName");

I want to know how many ways there are to do this is and which approach to use in which scenario.

Examples:

  • Activator.CreateInstance
  • Assembly.GetExecutingAssembly.CreateInstance("")
  • Any other suggestions would be appreciated

This question is not meant to be an open ended discussion because I am sure there are only so many ways this can be achieved.


回答1:


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);
}



回答2:


Activator.CreateInstance(Type.GetType("SomeNamespace.SomeClassName"));

or

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

There are also overloads where you can specify constructor arguments.



来源:https://stackoverflow.com/questions/9854900/instantiate-a-class-from-its-textual-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!