C#利用反射動態綁定事件

大多數時都是強類型,直接綁定事件,但這種耦合關係太強,在動態調用Dll的時候就不太合適了。ide

如下是動態綁定和直接綁定的一個簡單實例:this

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Threading.Tasks;
  6 //
  7 using System.Reflection;
  8 
  9 namespace 反射綁定事件及方法
 10 {
 11     class Program
 12     {
 13         static void Main(string[] args)
 14         {
 15             //普通綁定事件實例
 16             NormalBindingEvent();
 17 
 18             //反射綁定事件實例
 19             ReflectionBindingEvent();
 20 
 21             //控制檯提示
 22             ConsoleTips();
 23         }
 24 
 25         /// <summary>
 26         /// 反射綁定事件
 27         /// </summary>
 28         static void ReflectionBindingEvent()
 29         {
 30             var customerRef = new CustomerClass();
 31             EventInfo evtInfo = customerRef.GetType().GetEvent("MyEvent", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
 32             evtInfo.AddEventHandler(customerRef, new EventHandler(CustomerObj_CustomerEvent));
 33 
 34             //觸發事件,傳遞參數
 35             customerRef.TirggerEvent("hello 我是反射綁定");
 36         }
 37 
 38         /// <summary>
 39         /// 常規的事件綁定處理
 40         /// </summary>
 41         static void NormalBindingEvent()
 42         {
 43             var CustomerObj = new CustomerClass();
 44             CustomerObj.MyEvent += new EventHandler(CustomerObj_CustomerEvent);
 45 
 46             //觸發事件,傳遞參數
 47             CustomerObj.TirggerEvent("Hello 個人常規綁定");
 48         }
 49 
 50         static void CustomerObj_CustomerEvent(object sender, EventArgs e)
 51         {
 52             string msg = ((myEventArgs)e).StrInfo;
 53             Console.WriteLine("事件已被觸發,接受到參數:{0}", msg);
 54         }
 55 
 56 
 57 
 58         static void ConsoleTips()
 59         {
 60             Console.WriteLine(" ");
 61             Console.Write("請按任意鍵退出...");
 62             Console.ReadKey();
 63         }
 64     }
 65 
 66     public class CustomerClass
 67     {
 68 
 69         /// <summary>
 70         /// 自定義事件
 71         /// </summary>
 72         public event EventHandler MyEvent;
 73 
 74         //觸發事件的方法
 75         /// <summary>
 76         /// 
 77         /// </summary>
 78         /// <param name="info"></param>
 79         public void TirggerEvent(string info)
 80         {
 81             if (MyEvent != null)
 82             {
 83                 EventArgs eArg = new myEventArgs(info);
 84                 MyEvent(this, eArg);
 85             }
 86         }
 87     }
 88 
 89     //聲明事件信息類型,並繼承於EventArgs
 90     class myEventArgs : EventArgs
 91     {
 92         public myEventArgs(string strinfo)
 93         {
 94             this.strinfo = strinfo;
 95         }
 96         private string strinfo;
 97         public string StrInfo
 98         {
 99             get { return strinfo; }
100         }
101     }
102 }
代碼
相關文章
相關標籤/搜索