使用类型调用静态方法
问题描述:
假设我知道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()
运营商。
答
你需要调用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");
感谢伊戈尔,这将工作正常(虽然我对C#感到失望 - 它看起来完全没有类型安全) 在我的实际代码中有很多类可能在Type变量中,所以反射是必需的。 – MrEff 2010-08-02 16:24:35