c# - 如何使用反射调用通用扩展方法?

标签 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));
    }
}

怎么了?

最佳答案

扩展方法没有附加到 Form 类型,它附加到 MyClass 类型,所以从那个类型中获取它:

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

关于c# - 如何使用反射调用通用扩展方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15927028/

相关文章:

c# - 使 UWP 颜色选择器更小或更大

c# - 犀牛模拟 : How to stub a generic method to catch an anonymous type?

java - 为什么这个泛型引用不能指向Java中这个类似的扩展类?

c# - 实现接口(interface)

c# - 通过泛型访问扩展方法总是匹配最不具体的选项?

C#扩展方法重载导致 "missing assembly reference"错误

c# - Onclick 事件在其下方显示一条红线

c# - 如何根据当前服务器找到最适合读取或写入 Stream 的缓冲区大小

c# - 有什么方法可以在 C# 的对象初始化程序 block 中使用扩展方法

c# - 在 C# 中获取 OutOfMemoryException 的最简单方法是什么?