如何调用一个动态方法来返回数字的平方

本文关键字:数字 返回 方法 一个 何调用 调用 动态 | 更新日期: 2023-09-27 18:27:55

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

我怎样才能让这东西发挥作用?

如何调用一个动态方法来返回数字的平方

您有几个问题。首先,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 );
    }
}