0

我想创建一个简单的动态方法,它返回整数的平方(即 - 如果数字是 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);

我怎样才能让这个东西工作?

4

1 回答 1

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 );

    }
}
于 2014-10-27T16:34:02.030 回答