using System; using System.IO; using System.Reflection; using System.Reflection.Emit; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { Type[] par = new Type[] { typeof(Int32), typeof(Int32) }; DynamicMethod func = new DynamicMethod("AddTwoValues", typeof(Int32), par, false); ILGenerator il = func.GetILGenerator(); // : int AddTwoValues(int x, int y) { return x+y; } il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Add); il.Emit(OpCodes.Ret); Object[] param = new Object[] { 13, 12 }; // 12 13 int iRet=(int)func.Invoke(null, param); // // Console.WriteLine("{0}+{1}={2}", param[0], param[1], iRet); } } }
using System; using System.IO; using System.Reflection; using System.Reflection.Emit; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { Type[] par = new Type[] { typeof(Int32), typeof(Int32) }; DynamicMethod func = new DynamicMethod("AddTwoValues", typeof(Int32), par, false); ILGenerator il = func.GetILGenerator(); MethodInfo fnWriteLine = typeof(Console). GetMethod("WriteLine", new Type[] { typeof(Int32) }); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Call, fnWriteLine); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Call, fnWriteLine); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Add); il.Emit(OpCodes.Ret); Object[] param = new Object[] { 13, 12 }; // 12 13 int iRet=(int)func.Invoke(null, param); // // Console.WriteLine("{0}+{1}={2}", param[0], param[1], iRet); } } }
120 31/12/2017
Source: https://habr.com/ru/post/327580/
All Articles