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("")
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.
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:
assembly
to whatever you need)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);
}
Activator.CreateInstance(Type.GetType("SomeNamespace.SomeClassName"));
or
Activator.CreateInstance(null, "SomeNamespace.SomeClassName").Unwrap();
There are also overloads where you can specify constructor arguments.
使用这种方式来使用没有完全限定命名空间的类名:
System.Reflection.Assembly.GetExecutingAssembly().CreateInstance("myclass");
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.