如果我知道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
}
}
}
因此,给定Type t
,目标是在FooMethod()
的类上调用Type t
。基本上我需要反转typeof()
运算符。
答案 0 :(得分:50)
您需要调用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 - means calling static method
}
}
}
当然,在上面的示例中,您也可以调用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 - means calling static method
}
}
}
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");
答案 1 :(得分:2)
检查MethodInfo类和Type上的GetMethod()方法。
针对不同情况,存在许多不同的重载。
答案 2 :(得分:0)
请注意,已经过去了10年。我个人将添加扩展方法:
public static TR Method<TR>(Type t, string method, object obj = null, params object[] parameters)
=> (TR)t.GetMethod(method)?.Invoke(obj, parameters);
然后我可以打电话给
var result = typeof(Foo1Class).Method<string>(nameof(Foo1Class.Foo1Method));