代码之家  ›  专栏  ›  技术社区  ›  Dathan

使用反射创建泛型委托

  •  12
  • Dathan  · 技术社区  · 15 年前

    我有以下代码:

    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 可能有几百万次,我希望能够创建一个委托并将其缓存为一个小型优化。

    1 回复  |  直到 15 年前
        1
  •  8
  •   Reed Copsey    15 年前

    方法不是静态方法,因此需要使用:

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

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