private static void CreateMethod() { DynamicGenerator proxy = new DynamicGenerator(); var assembly = proxy.GetAssemblyBuilder(); var module = proxy.GetModuleBuilder(assembly); var typeBuilder = proxy.GetTypeBuilder(module, "DynamicProxyClass"); Type[] tparams = { typeof(int), typeof(int) }; MethodBuilder methodSum = proxy.GetMethod(typeBuilder, "Sum", typeof(int), tparams); ILGenerator generator = methodSum.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldarg_1); generator.Emit(OpCodes.Add_Ovf); generator.Emit(OpCodes.Stloc_0); generator.Emit(OpCodes.Br_S); generator.Emit(OpCodes.Ldloc_0); generator.Emit(OpCodes.Ret); Type type = typeBuilder.CreateType(); var obj = Activator.CreateInstance(type); var ret = obj.GetType().GetMethod("Sum").Invoke(obj, new object[] { 2, 3 }); Console.WriteLine(ret); }
private object CreateInstanceInternal(Type serviceType, Type implementType) { var assemblyBuilder = _generator.GetAssemblyBuilder(); var moduleBuilder = _generator.GetModuleBuilder(assemblyBuilder); var typeBuilder = moduleBuilder.DefineType("DynamicProxy_" + implementType.Name, TypeAttributes.Public, null, new Type[] { serviceType }); //定义构造函数 var constructor = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Type.EmptyTypes); var constructorInfo = implementType.GetConstructor(Type.EmptyTypes); //FieldBuilder _serviceImpObj = typeBuilder.DefineField("_serviceImpObj", implementType, FieldAttributes.Private); //初始化 var constructIL = constructor.GetILGenerator(); constructIL.Emit(OpCodes.Ldarg_0); constructIL.Emit(OpCodes.Call, constructorInfo); //constructIL.Emit(OpCodes.Newobj, implementType.GetConstructor(Type.EmptyTypes)); //constructIL.Emit(OpCodes.Stfld, _serviceImpObj); constructIL.Emit(OpCodes.Ret); //方法体 var methodInfos = serviceType.GetTypeInfo().GetMethods(BindingFlags.Public | BindingFlags.Instance); foreach (var method in methodInfos) { if (_ignoreMethods.Contains(method.Name)) { continue; } var parameterTypes = method.GetParameters().Select(p => p.ParameterType).ToArray(); var methodBuilder = typeBuilder.DefineMethod(method.Name, MethodAttributes, CallingConventions.HasThis, method.ReturnType, parameterTypes); var methodIL = methodBuilder.GetILGenerator(); methodIL.Emit(OpCodes.Ldarg_0); //methodIL.Emit(OpCodes.Ldfld, constructorInfo); //加载参数 for (int i = 0; i < parameterTypes.Length; i++) { methodIL.Emit(OpCodes.Ldarg, i + 1); } methodIL.Emit(OpCodes.Callvirt, implementType.GetMethod(method.Name)); methodIL.Emit(OpCodes.Ret); } var type = typeBuilder.CreateTypeInfo(); return(Activator.CreateInstance(type)); }