使用Type调用静态方法

MrE*_*Eff 38 c#

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

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,给定一个Type t,目标是调用FooMethod()该类Type t.基本上我需要反转typeof()操作员.

Igo*_*aka 53

你需要调用MethodInfo.Invoke方法:

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当然在上面的例子中你也可以这样称呼,FooClass.FooMethod因为没有必要使用反射.以下示例更有意义:

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");    
Run Code Online (Sandbox Code Playgroud)


Mar*_*gus 5

请注意,10 年过去了。就我个人而言,我会添加扩展方法:

public static TR Method<TR>(this Type t, string method, object obj = null, params object[] parameters) 
    => (TR)t.GetMethod(method)?.Invoke(obj, parameters);
Run Code Online (Sandbox Code Playgroud)

然后我可以这样调用它:

var result = typeof(Foo1Class).Method<string>(nameof(Foo1Class.Foo1Method));
Run Code Online (Sandbox Code Playgroud)