有两个 Assembly A,B 在A中声明了一个事件(某个类中的某个事件), B没有引用这Assembly ,但是想挂A中的这个事件。当A中的某个逻辑fire这个Event时,B挂事件的地方要(B的handler)要做些事情。
FireFarEvent 是 Assembly A, MainForm 类公开一个 SomeEvent 事件, FireEvent button 会 Fire 这个 Event.
AttachFarEvent 是 Assembly B, AttachFarEventForm 中 btnAttachEvent_Click 会 hook FireFarEvent 中的 SomeEvent.
AttachFarEvent代码如下:
1 |
private void btnDetachEvent_Click( object sender, EventArgs e) |
3 |
if (assembly == null || fireEventForm == null || farEventEventInfo == null ) |
5 |
MessageBox.Show( "Please click the first button to load the fire event form." ); |
8 |
farEventEventInfo.RemoveEventHandler(fireEventForm, farEventDelegate); |
Demo下载:AttachFarEvent.rar
01 |
private void btnAttachEvent_Click( object sender, EventArgs e) |
03 |
if (assembly == null || fireEventForm == null ) |
05 |
MessageBox.Show( "Please click the first button to load the fire event form." ); |
08 |
Type fireFarEventFormType = fireEventForm.GetType(); |
09 |
farEventEventInfo = fireFarEventFormType.GetEvent( "SomeEvent" ); |
11 |
EventHandler tempHandler = new EventHandler( this .farEventHandler); |
12 |
MethodInfo tempHandlerMethodInfo = tempHandler.Method; |
15 |
DynamicMethod dynamicMethod = new DynamicMethod( |
16 |
"BridgeMethodForAttachEvent" , typeof ( void ), |
17 |
new Type[] { typeof ( object ), assembly.GetType( "FireFarEvent.FarEventArgs" ) }, |
20 |
ILGenerator il = dynamicMethod.GetILGenerator(); |
23 |
il.Emit(OpCodes.Ldarg_0); |
24 |
il.Emit(OpCodes.Ldarg_2); |
25 |
il.Emit(OpCodes.Ldarg_1); |
26 |
il.Emit(OpCodes.Call, tempHandlerMethodInfo); |
30 |
dynamicMethod.DefineParameter(1, ParameterAttributes.In, "object" ); |
31 |
dynamicMethod.DefineParameter(2, ParameterAttributes.In, "e" ); |
33 |
farEventDelegate = dynamicMethod.CreateDelegate(farEventEventInfo.EventHandlerType); |
34 |
farEventEventInfo.AddEventHandler(fireEventForm, farEventDelegate); |
DetachFarEvent代码如下: