整数の 2 乗を返す単純な動的メソッドを作成したいと考えています (つまり、数値が 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);
どうすればこれを機能させることができますか?