什么是委托,事件
之前一直不明白什么是委托与事件,网上的介绍可谓纷繁复杂。晦涩难懂,今天写一个看门大爷都能看懂的委托,事件的实例。话不多说,直接上代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 委托事件实例 { class Program { static void Main(string[] args) { A a = new A();//定义首领A B b = new B(a);//定义部下B C c = new C(a);//定义部下C //首领A左手举起 a.Raise("左"); //首领A右手举起 a.Raise("右"); //首领A摔杯 a.Fall(); Console.WriteLine(); //由于B,C订阅了事件A所以无需任何代码,BC均会按照约定进行动作 } } /// <summary> /// 首领A举杯委托 /// </summary> /// <param name="hand"></param> public delegate void RaiseEventHandler(string hand); /// <summary> /// 首领A摔杯委托 /// </summary> public delegate void FallEventHandler(); /// <summary> /// 首领A /// </summary> public class A { /// <summary> /// 首领A举杯事件 /// </summary> public event RaiseEventHandler RaiseEvent; /// <summary> /// 首领A摔杯事件 /// </summary> public event FallEventHandler FallEvent; /// <summary> /// 举杯 /// </summary> /// <param name="hand"></param> public void Raise(string hand) { Console.WriteLine("首领A{0}手举杯",hand); //调用举杯事件,传入或者右手作为参数 if (RaiseEvent != null) { RaiseEvent(hand); } } /// <summary> ///调用摔杯事件 /// </summary> public void Fall() { Console.WriteLine("首领A摔杯"); //调用摔杯事件 if (FallEvent!= null) { FallEvent(); } Console.ReadKey(); } } public class B { A a; public B(A a) { this.a = a; a.RaiseEvent += new RaiseEventHandler(a_RaiseEvent);//订阅举杯事件 a.FallEvent += new FallEventHandler(a_FallEvent);//订阅摔杯事件 } /// <summary> /// 首领举杯时的动作 /// </summary> /// <param name="hand"></param> void a_RaiseEvent(string hand) { if (hand.Equals("左")) { Attack(); } } /// <summary> /// 首领摔杯时的动作 /// </summary> void a_FallEvent() { Attack(); } /// <summary> /// 攻击 /// </summary> public void Attack() { Console.WriteLine("部下B发起攻击,大喊:张飞来也!"); } } public class C { A a; public C(A a) { this.a = a; a.RaiseEvent += new RaiseEventHandler(a_RaiseEvent); a.FallEvent += new FallEventHandler(a_FallEvent); } /// <summary> /// A举杯时的动作 /// </summary> /// <param name="hand"></param> void a_RaiseEvent(string hand) { if (hand.Equals ("右")) { Attack(); } } /// <summary> /// A摔杯子时的动作 /// </summary> void a_FallEvent() { Attack(); } public void Attack() { Console.WriteLine("部下C发起进攻,大喊:关羽在此"); } } }