【问题标题】:Create generic delegate using reflection使用反射创建通用委托
【发布时间】:2010-03-10 19:01:41
【问题描述】:

我有以下代码:

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];
    }
}

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

【问题讨论】:

    标签: c# .net generics reflection delegates


    【解决方案1】:

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

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

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

    【讨论】:

    • 噢!非常感谢 - 不知道我是怎么错过的。
    猜你喜欢
    • 2011-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多