Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Reflection.Emit;
- namespace ConsoleApp2
- {
- class Program
- {
- public static void Main()
- {
- int invokationOfHandMadeMethodResult = Calculate(10);
- Console.WriteLine(invokationOfHandMadeMethodResult);
- int invokationOfDynamicallyCreatedMethodResult = CreateCalculateMethod()(10);
- Console.WriteLine(invokationOfDynamicallyCreatedMethodResult);
- }
- public static Func<int, int> CreateCalculateMethod()
- {
- Type integerType = typeof(int);
- DynamicMethod dynamicMethod = new DynamicMethod("Calculate", integerType, new[] { integerType });
- //----------------------------------------------------------------
- ILGenerator il = dynamicMethod.GetILGenerator();
- Label loopStartLable = il.DefineLabel();
- Label methodReturnResultLable = il.DefineLabel();
- //-- Local variable [0] -> int result
- il.DeclareLocal(integerType);
- il.Emit(OpCodes.Ldc_I4_0);
- il.Emit(OpCodes.Stloc_0);
- //-- Local variable [1] -> int i
- il.DeclareLocal(integerType);
- il.Emit(OpCodes.Ldc_I4_0);
- il.Emit(OpCodes.Stloc_1);
- //-- Loop start check -> i < 10
- il.MarkLabel(loopStartLable);
- il.Emit(OpCodes.Ldloc_1);
- il.Emit(OpCodes.Ldc_I4, 10);
- il.Emit(OpCodes.Bge, methodReturnResultLable);
- //-- Loop body -> result += i * x (The next THREE steps)
- //-- 1. i * x
- il.Emit(OpCodes.Ldloc_1);
- il.Emit(OpCodes.Ldarg_0);
- il.Emit(OpCodes.Mul);
- //-- 2. result + (i * x)
- il.Emit(OpCodes.Ldloc_0);
- il.Emit(OpCodes.Add);
- //-- 3. result = result + (i * x)
- il.Emit(OpCodes.Stloc_0);
- //-- i++
- il.Emit(OpCodes.Ldloc_1);
- il.Emit(OpCodes.Ldc_I4_1);
- il.Emit(OpCodes.Add);
- il.Emit(OpCodes.Stloc_1);
- //-- Branch/Go to the beginning of the loop and repeat
- il.Emit(OpCodes.Br, loopStartLable);
- //-- End of method -> return result
- il.MarkLabel(methodReturnResultLable);
- il.Emit(OpCodes.Ldloc_0);
- il.Emit(OpCodes.Ret);
- //----------------------------------------------------------------
- Func<int, int> method = (Func<int, int>)dynamicMethod.CreateDelegate(typeof(Func<int, int>));
- return method;
- }
- public static int Calculate(int x)
- {
- int result = 0;
- for (int i = 0; i < 10; i++)
- {
- result += i * x;
- }
- return result;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement