public static void Say() { //定义动态方法 DynamicMethod method = new DynamicMethod("Hello", null, null); //创建MSIL生成器,为动态方法生成代码 ILGenerator helloIL = method.GetILGenerator(); //加载字符参数 helloIL.Emit(OpCodes.Ldstr, "hello world!"); //调用Console.WriteLine方法输出 helloIL.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) })); //方法结束,返回 helloIL.Emit(OpCodes.Ret); //完成动态方法的创建,获取一个可执行该动态方法的委托 HelloWorldDelegate helloDelegate = method.CreateDelegate(typeof(HelloWorldDelegate)) as HelloWorldDelegate; //执行动态方法 helloDelegate(); }
/// <summary> /// hello world 方法 /// </summary> private static void Helloworld() { //定义一个名为HellWorld的动态方法,没有返回值,没有参数 DynamicMethod helloWorldMethod = new DynamicMethod("HelloWorld", null, null); //创建一个MSIL生成器,为动态方法生成代码 ILGenerator helloWorldIL = helloWorldMethod.GetILGenerator(); //将要输出的HelloWorld!字符串加载到堆栈上 helloWorldIL.Emit(OpCodes.Ldstr, "Hello World!"); //调用Console.WreiteLine(string)方法输出Hello World! helloWorldIL.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) })); //方法结束,返回 helloWorldIL.Emit(OpCodes.Ret); //完成动态方法的创建,并且获取一个可以执行该动态方法的委托 HelloWorldDelegate HelloWorld = (HelloWorldDelegate)helloWorldMethod.CreateDelegate(typeof(HelloWorldDelegate)); //执行动态方法,将在屏幕上打印Hello World! HelloWorld(); }