我想创建一个简单的动态方法,它返回一个整数的平方(即 - 如果数字是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);
我怎样才能让这件事起作用?
答案 0 :(得分:2)
你有几个问题。首先,Square类必须是公共的,其CalculateSquare方法必须是静态的。其次,如果要调用方法乘以,则不想发射Mul。以下是包含这些修复的代码:
public class Square
{
public static 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 );
// Call the overload of CalculateSquare that returns the square of number
il.Emit( OpCodes.Call, getSquare );
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 );
}
}