Пример: ускорение API отражения с помощью делегата в .NET / C #

Как спрашивается в этом сообщении , я придумал пример, в котором используется Delegate для ускорения Refection в .NET / C #.

Однако я получил эту ошибку при запуске (компиляция работает отлично). Что может быть не так?

Unhandled Exception: System.ArgumentException: type is not a subclass of Multicastdelegate
  at System.Delegate.CreateDelegate (System.Type type, System.Object firstArgument, System.Reflection.MethodInfo method, Boolean throwOnBindFailure, Boolean allowClosed) [0x00000] in :0 
  at System.Delegate.CreateDelegate (System.Type type, System.Reflection.MethodInfo method, Boolean throwOnBindFailure) [0x00000] in :0 
  at System.Delegate.CreateDelegate (System.Type type, System.Reflection.MethodInfo method) [0x00000] in :0 
  at EX.RefTest.DelegateTest () [0x00000] in :0 
  at EX.RefTest.Main () [0x00000] in :0 

ДОБАВЛЕНО

Это (рабочий) исходный код благодаря помощи Jon & ChaosPandion.

using System.Reflection;
using System;

namespace EX
{
    public class Hello
    {
        // properties
        public int Valx {get; set;}
        public int Valy {get; set;}
        public Hello()
        {
            Valx = 10; Valy = 20;
        }
        public int Sum(int x, int y)
        {
            Valx = x; Valy = y;
            return (Valx + Valy);
        }
    }
    public class RefTest
    {
        static void DelegateTest()
        {
            Hello h = new Hello();
            Type type = h.GetType();
            MethodInfo m = type.GetMethod("Sum");

            // Wrong! Delegate call = Delegate.CreateDelegate(type, m);
            Delegate call = Delegate.CreateDelegate(typeof(Func), h, m);
            int res = (int) call.DynamicInvoke(new object[] {100, 200});
            Console.WriteLine("{0}", res);
            // This is a direct method implementation from Jon's post, and this is much faster
            Func sum = (Func) Delegate.CreateDelegate(typeof(Func), h, m);
            res = sum(100, 200);
            Console.WriteLine("{0}", res);
        }
        static void Main()
        {
            DelegateTest();
        }
    }
}

ADDED2

Основываясь на ответе Джона, я провел тест производительности, чтобы использовать сумму 1000 время. По сравнению с методом использования (int) call.DynamicInvoke (new object [] {100, 200}); , Func sum = (Func ) Delegate.CreateDelegate (typeof (Func ), h, m); в 300 раз быстрее.

5
задан Community 23 May 2017 в 12:23
поделиться