c# - 使用反射创建通用委托(delegate)

标签 c# .net generics reflection delegates

我有以下代码:

class Program
{
    static void Main(string[] args)
    {
        new Program().Run();
    }

    public void Run()
    {
        // works
        Func<IEnumerable<int>> static_delegate = new Func<IEnumerable<int>>(SomeMethod<String>);

        MethodInfo mi = this.GetType().GetMethod("SomeMethod").MakeGenericMethod(new Type[] { typeof(String) });
        // throws ArgumentException: Error binding to target method
        Func<IEnumerable<int>> reflection_delgate = (Func<IEnumerable<int>>)Delegate.CreateDelegate(typeof(Func<IEnumerable<int>>), mi);

    }

    public IEnumerable<int> SomeMethod<T>()
    {
        return new int[0];
    }
}

为什么我不能为我的泛型方法创建委托(delegate)?我知道我可以只使用 mi.Invoke(this, null),但由于我可能要执行 SomeMethod 几百万次,所以我想能够创建一个委托(delegate)并将其缓存为一个小的优化。

最佳答案

你的方法不是静态方法,所以你需要使用:

Func<IEnumerable<int>> reflection_delgate = (Func<IEnumerable<int>>)Delegate.CreateDelegate(typeof(Func<IEnumerable<int>>), this, mi);

将“this”传递给第二个参数将允许该方法绑定(bind)到当前对象上的实例方法...

关于c# - 使用反射创建通用委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2419705/

相关文章:

c# - 根据从 C# 中的 SQL 查询返回的记录数动态创建多个数据表?

c# - 在另一个项目 c# 中使用引用项目的 WCF 服务

c# - .NET WebBrowser 控件是否可以使用 IE9?

java - 获取通用类类型

c# - "Class does not implement interface member"类实现通用接口(interface)时出错

c# - 如何从 C# 中使用 STARTUPINFOEX 调用 CreateProcess() 并重新设置子进程的父级

c# - 通过 HTTP 处理程序连接到 SQL Server Express 数据库

c# - 如何在winforms中禁用表格面板的水平滚动条

.net - 如何缓存css,图像和js?

java通用: Object<String> obj = new Object<~>();