使用类型调用静态方法 [英] Calling a static method using a Type

查看:99
本文介绍了使用类型调用静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我知道 Type 变量的值,如何从 Type 调用静态方法,并且静态方法的名称?

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

Type t ,目标是在 Type的类上调用 FooMethod() t 。基本上,我需要反转 typeof()运算符。

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.

推荐答案

您需要调用 MethodInfo.Invoke 方法:

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

当然,在上面的示例中,您最好调用 FooClass.FooMethod ,因为没有必要为此使用反射。以下示例更有意义:

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

这篇关于使用类型调用静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆