Iva*_*kin 8 .net c# il reflection.emit mono.cecil
我有以下C#代码:
public static double f2(Func<double, double> f, double x)
{
return f(x);
}
Run Code Online (Sandbox Code Playgroud)
这里是IL代码:
.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
}
Run Code Online (Sandbox Code Playgroud)
我该怎么发出
callvirt instance !1 class [mscorlib]System.Func`2<float64, float64>::Invoke(!0)
Run Code Online (Sandbox Code Playgroud)
通过System.Reflection.Emit或更好地通过Mono.Cecil进行操作?
什么!1和!0代表什么?
ulr*_*chb 10
该!n语法是一个通用的参数的引用.
在这个例子中......
!0是对第一个泛型参数的引用Func<double, double>(用作Invoke方法参数的类型)
!1是对第二个泛型泛型参数的引用Func<double, double>(用作返回类型Invoke)
编辑:你的方法使用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
Run Code Online (Sandbox Code Playgroud)
EDIT2:!n在提示@kvb之后纠正了解释
| 归档时间: |
|
| 查看次数: |
2510 次 |
| 最近记录: |