我想创建一个简单的动态方法,它返回整数的平方(即 - 如果数字是 5,它应该返回 25)。
我写了下面的代码: -
class Square
{
public int CalculateSquare(int value)
{ return value * value; }
}
public class DynamicMethodExample
{
private delegate int SquareDelegate(int value);
internal void CreateDynamicMethod()
{
MethodInfo getSquare = typeof(Square).GetMethod("CalculateSquare");
DynamicMethod calculateSquare = new DynamicMethod("CalculateSquare",
typeof(int),new Type[]{typeof(int)});
ILGenerator il = calculateSquare.GetILGenerator();
// Load the first argument, which is a integer, onto the stack.
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Mul);
// Call the overload of CalculateSquare that returns the square of number
il.EmitCall(OpCodes.Call, getSquare,null);
il.Emit(OpCodes.Ret);
SquareDelegate hi =
(SquareDelegate)calculateSquare.CreateDelegate(typeof(SquareDelegate));
Console.WriteLine("\r\nUse the delegate to execute the dynamic method:");
int retval = hi(42);
Console.WriteLine("Calculate square returned " + retval);
}
}
为什么我会收到“InvalidProgramException”
int retval = hi(42);
我怎样才能让这个东西工作?