C#利用反射动态绑定事件
大多数时都是强类型,直接绑定事件,但这种耦合关系太强,在动态调用Dll的时候就不太合适了。
以下是动态绑定和直接绑定的一个简单实例:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 }