掛載非引用Assembly中的事件

來源:互聯網
上載者:User

有兩個 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 }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.