Emit学习笔记
1,给字段设置值,并返回
static void Main(string[] args) { //给字段设置值,并返回 AssemblyName assemblyName = new AssemblyName("test"); var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave); var module = assemblyBuilder.DefineDynamicModule("test_module"); var typeBuilder = module.DefineType("produce_123", TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed); var method = typeBuilder.DefineMethod("aa", MethodAttributes.Public, CallingConventions.Standard, typeof(string), new Type[] { typeof(string) }); var fb = typeBuilder.DefineField("bb", typeof(string), FieldAttributes.Public); var li= method.GetILGenerator(); li.Emit(OpCodes.Ldarg_0);//获取this li.Emit(OpCodes.Ldarg_1);//获取aa方法的第一个参数 li.Emit(OpCodes.Stfld, fb);//设置bb字段的值 li.Emit(OpCodes.Ldarg_0);//获取this li.Emit(OpCodes.Ldfld, fb);//将bb字段压入栈 li.Emit(OpCodes.Ret);//返回值 var type = typeBuilder.CreateType(); var obj=Activator.CreateInstance(type); var aa= type.GetMethod("aa").Invoke(obj, new object[] { "aa" }); Console.WriteLine(aa); Console.ReadKey(); }
学习永不止境,技术成就梦想。