多路委托
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面向對象程式設計漫談》有關代理的内容
C#委托基礎系列原于2011年2月份發表在我的新浪部落格中,現在将其般至本部落格。
本文轉自IT徐胖子的專欄部落格51CTO部落格,原文連結http://blog.51cto.com/woshixy/1070981如需轉載請自行聯系原作者
woshixuye111