2013-04-10 1 views
8

연장 방법 GenericExtension을 작성했습니다. 이제 확장 메서드 Extension을 호출하고 싶습니다. 그러나 methodInfo 값은 항상 null입니다.리플렉션을 사용하여 일반 확장 메소드를 호출하는 방법은 무엇입니까?

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-generic-type? rq = 1을 참조하십시오. – skarmats

답변

15

확장 방법은 유형 Form에 연결되지 않은, 그것은 유형 MyClass에 부착하므로 해당 유형 떨어져 그것을 잡아 것 :

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

이제 저는 우울합니다 ... 솔루션은 매우 간단하고 명백합니다 감사합니다. – David

+0

@David, 걱정하지 마세요 ** ** 확장 메서드가 'Form' 유형에 첨부되어 있기 때문에 혼란스러워졌습니다. 두 번째 눈이 필요했습니다. –

-2

당신은 당신의 방법에 대한 일반 매개 변수로 문자열에 전달하는 ..

그러나 제약 조건은 T (문자열하지 않는) 양식에서 상속 할 필요가 있다고 말한다.

대신 typeof(MyForm) 또는 그와 같은 것을 쓰고 싶다고 가정합니다.