有兩個 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 }
本文配套源碼