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代码如下:
01 private void btnAttachEvent_Click(object sender, EventArgs e)
02 {
03 if(assembly == null || fireEventForm == null)
04 {
05 MessageBox.Show("Please click the first button to load the fire event form.");
06 return;
07 }
08 Type fireFarEventFormType = fireEventForm.GetType();
09 farEventEventInfo = fireFarEventFormType.GetEvent("SomeEvent");
10
11 EventHandler tempHandler = new EventHandler(this.farEventHandler); // for dynamic method.
12 MethodInfo tempHandlerMethodInfo = tempHandler.Method;
13
14
15 DynamicMethod dynamicMethod = new DynamicMethod(
16 "BridgeMethodForAttachEvent", typeof(void),
17 new Type[] { typeof(object), assembly.GetType("FireFarEvent.FarEventArgs") },
18 this.GetType());
19
20 ILGenerator il = dynamicMethod.GetILGenerator();
21
22 il.Emit(OpCodes.Nop);
23 il.Emit(OpCodes.Ldarg_0);
24 il.Emit(OpCodes.Ldarg_2);
25 il.Emit(OpCodes.Ldarg_1);
26 il.Emit(OpCodes.Call, tempHandlerMethodInfo);
27 il.Emit(OpCodes.Nop);
28 il.Emit(OpCodes.Ret);
29
30 dynamicMethod.DefineParameter(1, ParameterAttributes.In, "object");
31 dynamicMethod.DefineParameter(2, ParameterAttributes.In, "e");
32
33 farEventDelegate = dynamicMethod.CreateDelegate(farEventEventInfo.EventHandlerType);
34 farEventEventInfo.AddEventHandler(fireEventForm, farEventDelegate);
35 }
DetachFarEvent代码如下:
1 private void btnDetachEvent_Click(object sender, EventArgs e)
2 {
3 if (assembly == null || fireEventForm == null || farEventEventInfo == null)
4 {
5 MessageBox.Show("Please click the first button to load the fire event form.");
6 return;
7 }
8 farEventEventInfo.RemoveEventHandler(fireEventForm, farEventDelegate);
9 }