Emit介绍【转】
官方msdn地址介绍:
https://docs.microsoft.com/zh-cn/dotnet/api/system.reflection.emit?view=netframework-4.8
定义
在运行时构建一个程序集,然后创建类型
应用
动态代理
流程
1.用AssemblyBuilder构建程序集
需要先定义 assetblyName
//创建程序集名
AssemblyName aName = new AssemblyName("DynamicAssemblyExample");
//实例化AssemblyBuilder对象
AssemblyBuilder ab =
AppDomain.CurrentDomain.DefineDynamicAssembly(
aName,
AssemblyBuilderAccess.RunAndSave);
2.定义模块DefineDynamicModule创建ModuleBuilder
ModuleBuilder mb =
ab.DefineDynamicModule(aName.Name, aName.Name + ".dll");
3.创建动态类型TypeBuilder
TypeBuilder tb = mb.DefineType(
"MyDynamicType",
TypeAttributes.Public);
4.定义方法MethodBuilder
MethodAttributes getSetAttr = MethodAttributes.Public |
MethodAttributes.SpecialName | MethodAttributes.HideBySig;
MethodBuilder mbNumberGetAccessor = tb.DefineMethod(
"get_Number", // 方法名
getSetAttr, //方法修饰符
typeof(int), //返回值类型
Type.EmptyTypes);//传入类型的数组
5实现方法
ILGenerator numberSetIL = mbNumberSetAccessor.GetILGenerator();
// Load the instance and then the numeric argument, then store the
// argument in the field.
numberSetIL.Emit(OpCodes.Ldarg_0);
numberSetIL.Emit(OpCodes.Ldarg_1);
numberSetIL.Emit(OpCodes.Stfld, fbNumber);
numberSetIL.Emit(OpCodes.Ret);
6.创建类型并持久化到硬盘
根据自己的代码,改方法名和参数
Type type = typeBuilder.CreateType();
assemblyBuilder.Save(asmFileName);
object ob = Activator.CreateInstance(type);
for (int i = 1; i < 10; i++)
{
Console.WriteLine(type.GetMethod("MyMethod").Invoke(ob, new object[] { i }));
}
示例类
public class MyDynamicType
{
private int m_number;
public MyDynamicType() : this(42) {}
public MyDynamicType(int initNumber)
{
m_number = initNumber;
}
public int Number
{
get { return m_number; }
set { m_number = value; }
}
public int MyMethod(int multiplier)
{
return m_number * multiplier;
}
}