2011-12-10 20 views
6

C# gọiphát IL để gọi một hàm Math

Math.Pow(2,3); 

trong ILDASM:

ldc.r8 2. 
ldc.r8 3. 
call  float64[mscorlib]System.Math::Pow(float64, float64) 

Ai đó có thể xin vui lòng cho tôi biết làm thế nào để phát ra rằng tuyên bố cuộc gọi thông qua một ILGenerator? Cảm ơn.

Trả lời

14

Dưới đây là một ví dụ về việc xây dựng một phương pháp năng động mà sẽ gọi tĩnh Math.Pow(double, double) phương pháp:

using System; 
using System.Linq; 
using System.Reflection.Emit; 

class Program 
{ 
    static void Main() 
    { 
     // define the signature of the dynamic method 
     var powIt = new DynamicMethod(
      "PowIt", 
      typeof(double), 
      new Type[] { typeof(double), typeof(double) }, 
      typeof(Program).Module 
     ); 

     // get a MethodInfo pointer to the Math.Pow(double, double) static 
     // method that we are willing to use in our dynamic method 
     var pow = typeof(Math).GetMethod("Pow", new[] { typeof(double), typeof(double) }); 

     var il = powIt.GetILGenerator(); 
     // Push the first argument onto the evaluation stack 
     il.Emit(OpCodes.Ldarg_0); 
     // Push the second argument onto the evaluation stack 
     il.Emit(OpCodes.Ldarg_1); 
     // Invoke the Math.Pow static method that we obtained a MethodInfo earlier 
     // by passing the two arguments that are on the evaluation stack 
     il.Emit(OpCodes.Call, pow); 

     // Return from the method pushing a return value from the callee's evaluation stack onto the caller's evaluation stack 
     il.Emit(OpCodes.Ret); 

     // build a delegate from the dynamic method 
     var func = (Func<double, double, double>)powIt.CreateDelegate(typeof(Func<double, double, double>)); 

     // Now invoke the delegate 
     Console.WriteLine(func(2, 3)); 
    } 
} 
+0

Rất cám ơn - không thể đòi hỏi một ví dụ rõ ràng hơn. – tpascale

+0

bạn có thể giúp tôi với https://stackoverflow.com/questions/48160989/convert-loop-to-one-delegate?noredirect=1#comment83301610_48160989 –

Các vấn đề liên quan