Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a static method using a Type

Tags:

c#

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.

like image 534
MrEff Avatar asked Aug 02 '10 04:08

MrEff


People also ask

How do you call up a static method?

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.

Can I call a static method inside a regular one?

@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:: .

Can non-static constructor call static method?

Static method cannot cannot call non-static methods. Constructors are kind of a method with no return type.


1 Answers

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");     
like image 150
Igor Zevaka Avatar answered Oct 08 '22 03:10

Igor Zevaka