using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Reflection;
using System.Reflection.Emit;
namespace Emit
{
public class CModuleBuilder
{
public static void Demo(System.Windows.Controls.TextBlock outputBlock)
{
// 创建应用程序域.
AppDomain myCurrentDomain = AppDomain.CurrentDomain;
AssemblyName myAssemblyName = new AssemblyName("TempAssembly");
// 创建动态程序集
AssemblyBuilder myAssemblyBuilder = myCurrentDomain.DefineDynamicAssembly
(myAssemblyName, AssemblyBuilderAccess.Run);
// 动态模块.
ModuleBuilder myModuleBuilder = myAssemblyBuilder.
DefineDynamicModule("TempModule");
// 定义类.
TypeBuilder myTypeBuilder = myModuleBuilder.DefineType
("TempClass", TypeAttributes.Public);
// 添加字段.
FieldBuilder greetingField = myTypeBuilder.DefineField("Greeting",
typeof(String), FieldAttributes.Public);
Type[] myMethodArgs = { typeof(String) };
// 动态类的方法.
MethodBuilder myMethod = myTypeBuilder.DefineMethod("MyMethod",
MethodAttributes.Public, CallingConventions.Standard, typeof(String), myMethodArgs);
// 方法的属性.
MethodInfo stringConcat = typeof(String).GetMethod("Concat",
BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder,
new Type[] { typeof(String), typeof(String) },
null);
ILGenerator methodIL = myMethod.GetILGenerator();
methodIL.EmitWriteLine("In the method...");
methodIL.Emit(OpCodes.Ldarg_0);
methodIL.Emit(OpCodes.Ldarg_1);
methodIL.Emit(OpCodes.Stfld, greetingField);
methodIL.Emit(OpCodes.Ldstr, "Hello, ");
methodIL.Emit(OpCodes.Ldarg_1);
methodIL.Emit(OpCodes.Call, stringConcat);
methodIL.Emit(OpCodes.Ret);
Type myType = myTypeBuilder.CreateType();
MethodInfo myMethodInfo =
myType.GetMethod("MyMethod");
// Get the token used to identify the method within this module.
MethodToken myMethodToken =
myModuleBuilder.GetMethodToken(myMethodInfo);
outputBlock.Text += String.Format(
"Token used to identify the method of 'myType' within the module is {0:x}\n",
myMethodToken.Token);
object[] args = { "World!" };
object myObject = Activator.CreateInstance(myType);
outputBlock.Text += "Return value from MyMethod(\"World!\"): " +
myMethodInfo.Invoke(myObject, args);
}
}
}