Created
September 28, 2014 21:15
-
-
Save AlbertoMonteiro/d50d980a69a030f67f64 to your computer and use it in GitHub Desktop.
GerandoCodigoEmExecucao
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Reflection.Emit; | |
namespace GerandoCodigoEmExecucao | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Func<int, int, int> soma = Soma; | |
Func<int, int, int> somaDinamico = CriaMetodoSomador(); | |
Console.WriteLine(soma(1,2)); | |
Console.WriteLine(somaDinamico(1,2)); | |
var typeVoid = typeof(void); | |
var typeString = typeof(string); | |
var dynamicMethod = new DynamicMethod("Print", typeVoid, new[] { typeString }); | |
var writeLine = typeof (Console).GetMethod("WriteLine", new[] {typeString}); | |
var ilGenerator = dynamicMethod.GetILGenerator(); | |
ilGenerator.Emit(OpCodes.Ldarg_0); | |
ilGenerator.Emit(OpCodes.Call, writeLine); | |
ilGenerator.Emit(OpCodes.Ret); | |
dynamicMethod.Invoke(null, new[] {"Ola mundo!"}); | |
} | |
static Func<int, int, int> CriaMetodoSomador() | |
{ | |
var typeInt = typeof(int); | |
var dynamicMethod = new DynamicMethod("SomaValores", typeInt, new[] { typeInt, typeInt }); | |
var ilGenerator = dynamicMethod.GetILGenerator(); | |
ilGenerator.Emit(OpCodes.Ldarg_0); | |
ilGenerator.Emit(OpCodes.Ldarg_1); | |
ilGenerator.Emit(OpCodes.Add); | |
ilGenerator.Emit(OpCodes.Ret); | |
var assinatura = typeof(Func<int,int,int>); | |
return (Func<int, int, int>)dynamicMethod.CreateDelegate(assinatura); | |
} | |
static int Soma(int valorA, int valorB) | |
{ | |
return valorA + valorB; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment