How do I call a static method from a Type
, assuming I know the value of the Type
variable and the name of the static method?
public class FooClass { public static FooMethod() { //do something } } public class BarClass { public void BarMethod(Type t) { FooClass.FooMethod() //works fine if (t is FooClass) { t.FooMethod(); //should call FooClass.FooMethod(); compile error } } }
So, given a Type t
, the objective is to call FooMethod()
on the class that is of Type t
. Basically I need to reverse the typeof()
operator.
A static method can be called directly from the class, without having to create an instance of the class. A static method can only access static variables; it cannot access instance variables. Since the static method refers to the class, the syntax to call or refer to a static method is: class name. method name.
@Ian Dunn Put simply, $this only exists if an object has been instantiated and you can only use $this->method from within an existing object. If you have no object but just call a static method and in that method you want to call another static method in the same class, you have to use self:: .
Static method cannot cannot call non-static methods. Constructors are kind of a method with no return type.
You need to call MethodInfo.Invoke
method:
public class BarClass { public void BarMethod(Type t) { FooClass.FooMethod(); //works fine if (t == typeof(FooClass)) { t.GetMethod("FooMethod").Invoke(null, null); // (null, null) means calling static method with no parameters } } }
Of course in the above example you might as well call FooClass.FooMethod
as there is no point using reflection for that. The following sample makes more sense:
public class BarClass { public void BarMethod(Type t, string method) { var methodInfo = t.GetMethod(method); if (methodInfo != null) { methodInfo.Invoke(null, null); // (null, null) means calling static method with no parameters } } } public class Foo1Class { static public Foo1Method(){} } public class Foo2Class { static public Foo2Method(){} } //Usage new BarClass().BarMethod(typeof(Foo1Class), "Foo1Method"); new BarClass().BarMethod(typeof(Foo2Class), "Foo2Method");
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