如何用反射调用泛型扩展方法?

Dav*_*vid 10 c# generics extension-methods methodinfo

我写了扩展方法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));
    }
}
Run Code Online (Sandbox Code Playgroud)

怎么了?

Mik*_*oud 19

扩展方法没有附加到类型Form,它附加到类型MyClass,所以抓住它类型:

MethodInfo methodInfo = typeof(MyClass).GetMethod("GenericExtension",
    new[] { typeof(Form), typeof(string) });
Run Code Online (Sandbox Code Playgroud)