How can I get an instance of a static class with a string?
Example:
class Apple : IFruit
{
public static Apple GetInstance() { ... }
private Apple() { }
// other stuff
}
class Banana : IFruit
{
public static Banana GetInstance() { ... }
private Banana() { }
// other stuff
}
// Elsewhere in the code...
string fruitIWant = "Apple";
IFruit myFruitInstance = [What goes here using "fruitIWant"?].GetInstance();
Type appleType = Type.GetType("Apple");
MethodInfo methodInfo = appleType.GetMethod(
"GetInstance",
BindingFlags.Public | BindingFlags.Static
);
object appleInstance = methodInfo.Invoke(null, null);
Note that in Type.GetType you need to use the assembly-qualified name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With