C#委托基礎2——多路委托
C#委托基礎係列原於2011年2月份發表在我的新浪博客中,現在將其般至本博客。
多路委托
class Program { public delegate void SayThingToS(string s); void SayHello(string s) { Console.WriteLine("你好{0}", s); } void SayGoodBye(string s) { Console.WriteLine("再見{0}", s); } static void Main(string[] args) { // 方式一 SayThingToS say1, say2, say3, say4; Program p = new Program(); say1 = p.SayHello; say1("xy"); // 你好xy say2 = p.SayGoodBye; say2("xy"); // 再見xy say3 = say1 + say2; say3("xy"); // 你好xy,再見xy say4 = say3 - say1; say4("xy"); // 再見xy // 方式二 SayThingToS s1 = new SayThingToS(p.SayHello); s1 += new SayThingToS(p.SayGoodBye); s1("xy"); // 你好xy,再見xy SayThingToS s2 = new SayThingToS(p.SayHello); s2 += new SayThingToS(p.SayGoodBye); s2 -= new SayThingToS(p.SayHello); s2("xy"); // 再見xy } }
本文參考自金旭亮老師的《.NET 4.0麵向對象編程漫談》有關代理的內容
最後更新:2017-04-04 07:32:13