Emitting delegate function call

懵懂的女人 提交于 2019-12-04 03:45:24

The !n syntax is a reference to a generic argument.

In this example ...

!0 is a reference to the first generic argument of Func<double, double> (used as the type of the argument of the Invoke method)

!1 is a reference to the second generic generic argument of Func<double, double> (used as the return type of Invoke)

EDIT: Your method using System.Reflection.Emit ...

var dynamicMethod = new DynamicMethod(
    "f2Dynamic", 
    typeof(double), 
    new Type[] { typeof(Func<double, double>), typeof(double) });

var il = dynamicMethod.GetILGenerator();

il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Callvirt, typeof(Func<double, double>).GetMethod("Invoke"));
il.Emit(OpCodes.Ret);

var f2Dynamic = 
    (Func<Func<double, double>, double, double>)dynamicMethod.CreateDelegate(
        typeof(Func<Func<double, double>, double, double>));

Console.WriteLine(f2(x => x * x, 10.0));        // prints 100
Console.WriteLine(f2Dynamic(x => x * x, 10.0)); // prints 100

EDIT2: corrected the !n explanation after a hint of @kvb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!