发射委托函数调用 [英] Emitting delegate function call
问题描述
我有以下的C#code:
I have the following C# code:
public static double f2(Func<double, double> f, double x)
{
return f(x);
}
在这里,它是IL code:
And here it's IL code:
.method public hidebysig static
float64 f2 (
class [mscorlib]System.Func`2<float64, float64> f,
float64 x
) cil managed
{
// Method begins at RVA 0x20bd
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: callvirt instance !1 class [mscorlib]System.Func`2<float64, float64>::Invoke(!0)
IL_0007: ret
}
我怎样才能发出
How can I to emit
callvirt instance !1 class [mscorlib]System.Func`2<float64, float64>::Invoke(!0)
通过insturction在 System.Reflection.Emit 或通过更好的 Mono.Cecil能做到
什么!1!0是代表什么吗?
What !1 and !0 are stands for?
推荐答案
在 N!
语法引用一个通用的说法。
The !n
syntax is a reference to a generic argument.
在这个例子中...
0
是参照 Func键与其中的第一个通用参数;!双,双&GT;
(用作在调用
方法的参数类型)
!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
是参照 Func键与其中的第二个普通的一般的参数;!双,双&GT;
(作为的返回类型调用
)
!1
is a reference to the second generic generic argument of Func<double, double>
(used as the return type of Invoke
)
修改:使用方法 System.Reflection.Emit
...
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 :修正了 N
@kvb的暗示后解释
EDIT2: corrected the !n
explanation after a hint of @kvb
这篇关于发射委托函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!