c#学习笔记2-委托
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Demo { class Demo9 { //static void Main(string[] args) //{ // A a = new A(); // B b = new B(a); // C c = new C(a); // a.Fall(); // Console.ReadLine(); //} } /// <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} is ready", hand); // 调用举杯事件,传入左或右手作为参数 if (RaiseEvent != null) { RaiseEvent(hand); } } /// <summary> /// 摔杯 /// </summary> public void Fall() { Console.WriteLine("A is goods"); // 调用摔杯事件 if (FallEvent != null) { FallEvent(); } } } /// <summary> /// 部下B /// </summary> 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">若首领A左手举杯,则B攻击</param> void a_RaiseEvent(string hand) { if (hand.Equals("left")) { Attack(); } } /// <summary> /// 首领摔杯时的动作 /// </summary> void a_FallEvent() { Attack(); } /// <summary> /// 攻击 /// </summary> public void Attack() { Console.WriteLine("b attack"); } } /// <summary> /// 部下C /// </summary> 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> /// 首领举杯时的动作 /// </summary> /// <param name="hand">若首领A右手举杯,则攻击</param> void a_RaiseEvent(string hand) { if (hand.Equals("right")) { Attack(); } } /// <summary> /// 首领摔杯时的动作 /// </summary> void a_FallEvent() { Attack(); } /// <summary> /// 攻击 /// </summary> public void Attack() { Console.WriteLine("c attack"); } } }

更多精彩