2010-08-02 115 views
28

假設我知道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()運營商。

回答

39

你需要調用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");  
+0

感謝伊戈爾,這將工作正常(雖然我對C#感到失望 - 它看起來完全沒有類型安全) 在我的實際代碼中有很多類可能在Type變量中,所以反射是必需的。 – MrEff 2010-08-02 16:24:35