static void DynamicMethodExamples() { DynamicMethodGen dmg = DynamicMethodGen.Static <Program>().Void().Parameter <string>("name"); CodeGen g = dmg.GetCode(); g.Try(); { Operand name = g.Local <string>(g.Arg("name")); g.WriteLine("Hello {0}!", name); } g.CatchAll(); { g.WriteLine("Error"); } g.End(); DynamicMethod dm = dmg.GetCompletedDynamicMethod(true); // reflection-style invocation dm.Invoke(null, new object[] { "Dynamic Method" }); // delegate invocation var hello = dm.CreateDelegate <Action <string> >(); hello("Delegate"); }
static void DynamicMethodExamples() { DynamicMethodGen dmg = DynamicMethodGen.Static(typeof(Program)).Method(typeof(void)).Parameter(typeof(string), "name"); CodeGen g = dmg.GetCode(); g.Try(); { Operand name = g.Local(typeof(string), g.Arg("name")); g.WriteLine("Hello {0}!", name); } g.CatchAll(); { g.WriteLine("Error"); } g.End(); DynamicMethod dm = dmg.GetCompletedDynamicMethod(true); // reflection-style invocation dm.Invoke(null, new object[] { "Dynamic Method" }); // delegate invocation Action <string> hello = (Action <string>)dm.CreateDelegate(typeof(Action <string>)); hello("Delegate"); }