Advertisement
ar4ebald

Untitled

Jun 24th, 2016
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.83 KB | None | 0 0
  1. using System;
  2. using System.Reflection.Emit;
  3.  
  4. namespace MSILCalc
  5. {
  6.     class Program
  7.     {
  8.         private static readonly Type ReturnType = typeof(int);
  9.         private static readonly Type[] ParameterTypes = { typeof(int), typeof(int), typeof(int), typeof(int) };
  10.  
  11.         private static Func<int, int, int, int, int> Parse(string equation)
  12.         {
  13.             DynamicMethod dynamicMethod = new DynamicMethod("", ReturnType, ParameterTypes);
  14.             ILGenerator ilGenerator = dynamicMethod.GetILGenerator();
  15.  
  16.             foreach (char c in equation)
  17.             {
  18.                 switch (c)
  19.                 {
  20.                     case 'a':
  21.                         ilGenerator.Emit(OpCodes.Ldarg_0);
  22.                         break;
  23.                     case 'b':
  24.                         ilGenerator.Emit(OpCodes.Ldarg_1);
  25.                         break;
  26.                     case 'c':
  27.                         ilGenerator.Emit(OpCodes.Ldarg_2);
  28.                         break;
  29.                     case 'd':
  30.                         ilGenerator.Emit(OpCodes.Ldarg_3);
  31.                         break;
  32.                     case '+':
  33.                         ilGenerator.Emit(OpCodes.Add);
  34.                         break;
  35.                     case '*':
  36.                         ilGenerator.Emit(OpCodes.Mul);
  37.                         break;
  38.                 }
  39.             }
  40.  
  41.             ilGenerator.Emit(OpCodes.Ret);
  42.  
  43.             Delegate compiled = dynamicMethod.CreateDelegate(typeof(Func<int, int, int, int, int>));
  44.             return (Func<int, int, int, int, int>)compiled;
  45.         }
  46.  
  47.         static void Main(string[] args)
  48.         {
  49.             Func<int, int, int, int, int> intMethod = Parse("abcd+*+");
  50.             int result1 = intMethod(1, 2, 3, 4);
  51.             int result2 = intMethod(4, 3, 2, 1);
  52.         }
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement