【发布时间】:2020-05-17 20:35:34
【问题描述】:
我想使用reflection.emit API 调用带有参数的函数。以下是我目前所拥有的。但是当我运行它时,它会抛出以下异常:System.InvalidProgramException : Common Language Runtime detected an invalid program。所以我的问题是我在下面的代码 sn-p 中有什么问题?有人可以帮帮我吗?
public class Test
{
public void test()
{
Func<int, long> realSquareFunc = (val) => val * val;
Type[] methodArgs = { typeof(int) };
DynamicMethod squareIt = new DynamicMethod(
"SquareIt",
typeof(long),
methodArgs,
typeof(Test).Module)
;
ILGenerator il = squareIt.GetILGenerator();
il.Emit(OpCodes.Ldarg_0); // Save parameter on stack
il.Emit(OpCodes.Call, realSquareFunc.Method); // Call function with input as parameter
il.Emit(OpCodes.Ret); // Return value from function call before
var myMethod = (Func<int, long>)squareIt.CreateDelegate(realSquareFunc.GetType());
var result = myMethod.Invoke(4); // Should be 16 (4*4)
}
}
【问题讨论】:
标签: c# reflection func reflection.emit dynamicmethod