委托
委托约定方法签名
,引用一个或多个方法,调用委托就是调用委托引用的全部方法。
事件
类或对象通过事件向其他类或对象通知
发生的相关事情。
事件只能在定义的类内部调用;
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| using System; namespace SimpleTest { internal class Program { private static void Main(string[] args) { Publisher publisher = new Publisher(); Subscriber subscriber = new Subscriber(publisher); publisher.Trigger(); Console.ReadLine(); } }
public class Publisher { public delegate void NoticeHandler(string message); public event NoticeHandler OnNotice;
public void Trigger() { OnNotice?.Invoke("警告!警告!警告!警告"); } }
public class Subscriber { public Subscriber(Publisher pub) { pub.OnNotice += NoticeHandler; }
private void NoticeHandler(string message) { Console.WriteLine($"Notice Handler Got Message: {message}"); } } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| using System;
namespace MyConsole { public delegate string DelegateFun(string word);
public class Test { public event DelegateFun EventSay; public DelegateFun DelegateSay; public void DoEventSay(string str) { if (EventSay != null) { EventSay(str); } } }
internal static class Program { private static void Main(string[] args) { Test t = new Test(); t.EventSay += Say1; t.DelegateSay += Say1; t.DelegateSay += Say2;
t.DoEventSay("eventSay");
string str = t.DelegateSay("deleSay");
Console.Read(); }
private static string Say1(string word) { Console.WriteLine(word); return "return " + word; }
private static string Say2(string word) { Console.WriteLine(word); return "return " + word + " 2"; } } }
|