委托的自我理解:就是观察者与被观察者之间的行为事件。
父亲是被观察者
儿子是观察者
儿子随时观察父亲发出的命令
父亲只发布命令做什么,不关心儿子怎么去做
儿子收到父亲的委托命令,就去执行,
class Program { static void Main(string[] args) { Sender sender = new Sender(); Reciver reciver = new Reciver(sender); sender.SendMessage("去买东西"); Console.Read(); } } public delegate void SendMessageEventHandler(string msg);//定义委托 /// <summary> /// 父亲 /// </summary> class Sender { public event SendMessageEventHandler SendMessageEvent;//定义事件 public void SendMessage(string msg) { Console.WriteLine("Sender发布命令:" + msg); SendMessageEvent?.Invoke(msg);//调用事件 } } /// <summary> /// 儿子 /// </summary> class Reciver { Sender sender; public Reciver(Sender sender) { this.sender = sender; sender.SendMessageEvent += new SendMessageEventHandler(ReciveMessage);//订阅事件 } public void ReciveMessage(string msg) { Console.WriteLine("Reciver执行命令:" + msg); } }