MethodInfo tempHandlerMethodInfo = tempHandler.Method; DynamicMethod dynamicMethod = new DynamicMethod( "BridgeMethodForAttachEvent", typeof(void), new Type[ tempHandlerMethodInfo); il.Emit(OpCodes.Nop); il.Emit(OpCodes.Ret); dynamicMethod.DefineParameter (1, ParameterAttributes.In, "object"); dynamicMethod.DefineParameter(2, ParameterAttributes.In , "e"); farEventDelegate = dynamicMethod.CreateDelegate(farEventEventInfo.EventHandlerType
= new DynamicMethod("SetValue", null, new[] { typeof(A), typeof(int) }, typeof(A)); var ilGenerator = dynamicMethod.GetILGenerator(); ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit (typeof(Action<A, int>)); } private static Func<A, int> CreateGetDelegate() { var dynamicMethod = new DynamicMethod("GetValue", typeof(int), new[] { typeof(A) }, typeof(A)); var ilGenerator = dynamicMethod.GetILGenerator 其实原因也是显而易见的,我们自己编写的Emit代码中间有一层 DynamicMethod的委托调用,增加了开销,而 UnsafeAccessor它直接就是一个 staticexternintGetValueUnsafe
为了创建方法 public void Clone<T>(T source, T los) 我就使用了下面代码 var dynamicMethod = new DynamicMethod ILGenerator generator = dynamicMethod.GetILGenerator(); 需要获得类型的所有属性,虽然这里用了反射,但是只是用一次,因为这里用反射获得方法是在写IL = new DynamicMethod("Clone", null, new[] { typeof(T), typeof(T) }); ILGenerator generator = dynamicMethod.GetILGenerator(); foreach (var temp in typeof(T).GetProperties().Where( = dynamicMethod.GetILGenerator(); foreach (var temp in typeof(T).GetProperties().Where(
为了创建方法 public void Clone<T>(T source, T los) 我就使用了下面代码 var dynamicMethod = new DynamicMethod ILGenerator generator = dynamicMethod.GetILGenerator(); 需要获得类型的所有属性,虽然这里用了反射,但是只是用一次,因为这里用反射获得方法是在写IL = new DynamicMethod("Clone", null, new[] { typeof(T), typeof(T) }); ILGenerator generator = dynamicMethod.GetILGenerator(); foreach (var temp in typeof(T).GetProperties().Where( = dynamicMethod.GetILGenerator(); foreach (var temp in typeof(T).GetProperties().Where(
接下来,需要在运行时创建一个新的方法,很简单,没有参数,只是创建一个Employee对象然后直接返回 Employee DynamicMethod() { return new Employee (); } 这里主要使用到了 System.Reflection.Emit.DynamicMethod 动态创建方法 DynamicMethod dynamic = new("DynamicMethod ", typeof(Employee), null, typeof(ReflectionBenchmarks).Module, false); 创建了一个 DynamicMethod 对象,然后指定了方法名 expressionActivator = Expression.Lambda<Func<Employee>>(Expression.New(typeof(Employee))).Compile(); DynamicMethod dynamic = new("DynamicMethod", typeof(Employee), null, typeof(ReflectionBenchmarks).Module, false);
4,DynamicMethod 定义方法与添加 IL 下面我们来为 类型创建一个方法,并通过 Emit 向程序集中动态添加 IL。 目前我们已经获得了上面两大部分的信息,接下来我们使用 DynamicMethod 来动态编写方法。 定义 Add 方法并获取 IL 生成工具: DynamicMethod dynamicMethod = new DynamicMethod("Add",typeof(int),new DynamicMethod 用于定义一个方法;ILGenerator是 IL 生成器。 dynamicMethod = new DynamicMethod("Add", typeof(int), new Type[] { typeof(int), typeof(int) },typeof
反射发出调用 这里只介绍反射发出的一项技术 DynamicMethod,.NET 2.0 新增此类。 使用 DynamicMethod 类在运行时定义轻量全局方法,然后使用委托执行这些方法。 针对 MyMath.Add 方法,调用比前面两种方式复杂些: var addMethod = typeof(MyMath).GetMethod("Add");var dynamicMethod = new DynamicMethod("", typeof(int), new[] { typeof(MyMath), typeof(int), typeof(int) });//var il = dynamicMethod.GetILGenerator 反射发出能绕过跳过 JIT 可见性检查,访问 private 成员(对于 DynamicMethod 类,请查看:DynamicMethod 构造函数 (String, Type, Type[], Boolean = new DynamicMethod("", typeof(int), new[] { typeof(MyMath), typeof(int), typeof(int) }); var
typeof(TestNewobj).GetConstructors().FirstOrDefault(s => s.GetParameters().Length > 0); DynamicMethod dynamicMethod = new DynamicMethod("CreateInstance", typeof(TestNewobj), new Type[] { typeof(int), typeof (int) });//创建一个动态方法,方法名称,返回值,入参 var il = dynamicMethod.GetILGenerator(); /调用构造方法,并传入0,1索引参数的值 il.Emit(OpCodes.Ret);//返回创建的对象 var objCreator = dynamicMethod.CreateDelegate method2 = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(int) });//输出数字 var dynamicMethod
下面是CreateGetFunction的实现:创建一个DynamicMethod对象,通过IL Emit调用属性的Getter方法,并将结果返回。 最后通过DynamicMethod的CreateDelegate方法创建一个Func<object,object>委托对象并在本地缓存起来,供或许的获取属性值操作之用。 1: private Func<object, object> CreateGetFunction() 2: { 3: //... 4: DynamicMethod 最后通过DynamicMethod的CreateDelegate方法创建一个Action<object,object>委托对象并在本地缓存起来,供后续的属性赋值操作之用。 1: private Action<object, object> CreateSetAction() 2: { 3: //... 4: DynamicMethod method
动态方法替代方案: // 使用DynamicMethod实现高性能动态代码 var dynamicMethod = new DynamicMethod("GetName", typeof(string) , new[] { typeof(Product) }); ILGenerator il = dynamicMethod.GetILGenerator(); il.Emit(OpCodes.Ldarg_ Product).GetProperty("Name").GetGetMethod()); il.Emit(OpCodes.Ret); var getter = (Func<Product, string>)dynamicMethod.CreateDelegate
: class, new() { public Func<List<T>, List
publicstatic FastInvokeHandler GetMethodInvoker(MethodInfo methodInfo) { DynamicMethod dynamicMethod =new DynamicMethod(string.Empty, typeof(object), new Type[] { typeof(object), typeof(object []) }, methodInfo.DeclaringType.Module); ILGenerator il = dynamicMethod.GetILGenerator(); } il.Emit(OpCodes.Ret); FastInvokeHandler invoder = (FastInvokeHandler)dynamicMethod.CreateDelegate
SetValue(); 31 } 32 33 public static void SetValue() 34 { 35 DynamicMethod dm = new DynamicMethod("SetValueMethod", null, new Type[] { /*typeof(object), typeof(object)*/ }, true 23 // IL_001f: nop 24 // IL_0020: ret 25 //} // end of method Program::Main 26 27 DynamicMethod dm = new DynamicMethod("SetValueMethod", null, new Type[] { /*typeof(object), typeof(object)*/ }, true
class ProxyGenerator { public static T CreateProxy<T>() where T : class, new() { var dynamicMethod = new DynamicMethod("CglibProxy", typeof(T), Type.EmptyTypes, typeof(ProxyGenerator).Module); var ilGenerator = dynamicMethod.GetILGenerator(); // Create a new instance of the target class OpCodes.Ret); // Create a delegate to the dynamic method var methodDelegate = (Func<T>)dynamicMethod.CreateDelegate
让我们一步步揭秘: 首先创建一个DynamicMethod对象,它将保存创建的IL代码。 在创建DynamicMethod对象时,必须告诉它签名是什么,在这里,它是一个通用的委托类型delegate T DeepCopyDelegate<T>(T original, CopyContext var dynamicMethod = new DynamicMethod( type.Name + "DeepCopier", typeof(T), // 委托返回的类型 typeof(CopierGenerator).Module, true); var il = dynamicMethod.GetILGenerator(); IL将会变得相当复杂 // C#: return result; il.Emit(OpCodes.Ldloc_0); il.Emit(OpCodes.Ret); return dynamicMethod.CreateDelegate
Debug.Assert(Indicator.Injected == true); } static MethodBase GenerateNewMethod() { var dynamicMethod = new DynamicMethodDefinition(typeof(Foobar).GetMethod("Invoke")); var il = dynamicMethod.GetILProcessor var ldTrue = il.Create(OpCodes.Ldc_I4_1); var setIndicator = il.Create(OpCodes.Call, dynamicMethod.Module.ImportReference (typeof(Indicator).GetProperty("Injected").SetMethod));il.InsertBefore(dynamicMethod.Definition.Body.Instructions.First (), setIndicator); il.InsertBefore(setIndicator, ldTrue); return dynamicMethod.Generate
在如下的代码中,我们创建了一个DynamicMethod类型表示的动态方法,以IL Emit的方式利用IL指令Call完成了针对InternalValue属性的Get方法的调用。 我们所需的Func<Foobar,int>委托最终由这个DynamicMethod对象创建而成。 ; var method = new DynamicMethod("GetInternalValue", typeof(int), new Type[] { typeof(Foobar) ; var method = new DynamicMethod("GetInternalValue", typeof(int), new Type[] { typeof(Foobar)
IsValidEventHandler方法用于验证指定的类型是否与EventHandler兼容(按照上面提及的标准进行验证),在Convert方法中我们通过Emit的方式创建了一个DynamicMethod paramTypes[i + 1] = destinationParameters[i].ParameterType; 56: } 57: DynamicMethod method = new DynamicMethod("WrappedEventHandler", null, paramTypes); 58: MethodInfo invoker
id ForwardingTarget_dynamicMethod(id self, SEL _cmd) { NSLog(@"没有找到方法:%@",NSStringFromSelector(_cmd + (BOOL)resolveInstanceMethod:(SEL)sel { class_addMethod(self.class, sel, (IMP)ForwardingTarget_dynamicMethod
Object CreateInstanceByEmit(ConstructorInfo constructor) { //动态方法 var dynamicMethod = new DynamicMethod(Guid.NewGuid().ToString("N"), typeof(Object), new[] { typeof(object[]) }, true); //方法IL ILGenerator il = dynamicMethod.GetILGenerator(); //实例化命令 /返回 il.Emit(OpCodes.Ret); //用FUNC去关联方法 var func = (Func<Object>)dynamicMethod.CreateDelegate