2013-04-10 82 views
8

我寫了擴展方法GenericExtension。現在我想調用擴展方法Extension。但methodInfo的值始終爲空。如何用反射調用通用擴展方法?

public static class MyClass 
{ 
    public static void GenericExtension<T>(this Form a, string b) where T : Form 
    { 
     // code... 
    } 

    public static void Extension(this Form a, string b, Type c) 
    { 
     MethodInfo methodInfo = typeof(Form).GetMethod("GenericExtension", new[] { typeof(string) }); 
     MethodInfo methodInfoGeneric = methodInfo.MakeGenericMethod(new[] { c }); 
     methodInfoGeneric.Invoke(a, new object[] { a, b }); 
    } 

    private static void Main(string[] args) 
    { 
     new Form().Extension("", typeof (int)); 
    } 
} 

怎麼了?

+0

參見http://stackoverflow.com/questions/5959219/how -to-use-reflection-to-get-extension-method-on-generic-type?rq = 1瞭解更多信息。 – skarmats 2013-04-10 13:23:55

回答

15

擴展方法沒有連接到類型Form,它附連到類型MyClass,因此抓住它關閉該類型:

MethodInfo methodInfo = typeof(MyClass).GetMethod("GenericExtension", 
    new[] { typeof(Form), typeof(string) }); 
+1

現在我很沮喪...解決方案是如此簡單明顯 謝謝 – David 2013-04-10 13:37:22

+0

@大衛,不用擔心,你只是感到困惑,因爲它**覺得**擴展方法附加到類型'窗體'。你只需要第二組眼睛。 – 2013-04-10 13:38:30

-2

您傳遞字符串作爲你的方法泛型參數..

但你的約束說,T需要從表繼承(其中字符串不)。

我假設你想寫typeof(MyForm)或其他的那樣。