在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
假想场景:01国际计算机语言大会上,各种计算机语言汇聚一堂,共同探讨计算机语言的发展趋势和优势。由于语言众多,主办方pc和mac决定给每位参会者10分钟发言机会。Code is cheap。看看它们都怎么说: 类图: 代码如下:
CsStudy
{ class DelegateStudy { interface IProgramLanguage { void Speak(); } class Java : IProgramLanguage { public void Speak() { Console.WriteLine("Java is the best."); } } class JavaScript : IProgramLanguage { public void Speak() { Console.WriteLine("JavaScript is the best."); } } class C : IProgramLanguage { public void Speak() { Console.WriteLine("C is the best."); } } class CSharp : IProgramLanguage { public void Speak() { Console.WriteLine("Oh really? C# is the best of best."); } } public delegate void LanguageSpeak(); //声明委托 LanguageSpeak programLs; public void BeginSpeak() { Console.WriteLine("Are you ready? Go!"); if (programLs != null) { programLs(); } } /// <summary> /// 客户端调用 /// </summary> static void Main(string[] args) { DelegateStudy ds = new DelegateStudy(); ds.programLs += new DelegateStudy.LanguageSpeak(new Java().Speak); ds.programLs += new DelegateStudy.LanguageSpeak(new JavaScript().Speak); ds.programLs += new DelegateStudy.LanguageSpeak(new C().Speak); ds.programLs += new DelegateStudy.LanguageSpeak(new CSharp().Speak); ds.BeginSpeak(); Console.Read(); } } } 委托总结: LanguageSpeak programLs = new LanguageSpeak(new CSharp().Speak); //关联 programLs(); //调用
CsStudy
{ using System; class DelegateStudy { interface IProgramLanguage { string Speak(string language); } class Java : IProgramLanguage { public string Speak(string language) { return string.Format( "{0} is the best.",language); } } class JavaScript : IProgramLanguage { public string Speak(string language) { return string.Format("{0} is the best.", language); } } class C : IProgramLanguage { public string Speak(string language) { return string.Format("{0} is the best.", language); } } class CSharp : IProgramLanguage { public string Speak(string language) { return string.Format("{0} is the best.", language); } } public delegate string LanguageSpeak(string language); //声明委托 LanguageSpeak programLs; /// <summary> /// 客户端调用 /// </summary> static void Main(string[] args) { DelegateStudy ds = new DelegateStudy(); ds.programLs = new DelegateStudy.LanguageSpeak(new Java().Speak); Console.WriteLine(ds.programLs("Java")); ds.programLs += new DelegateStudy.LanguageSpeak(new JavaScript().Speak); Console.WriteLine(ds.programLs("JavaScript")); ds.programLs += new DelegateStudy.LanguageSpeak(new C().Speak); Console.WriteLine(ds.programLs("C")); ds.programLs += new DelegateStudy.LanguageSpeak(new CSharp().Speak); Console.WriteLine(ds.programLs("C#")); Console.Read(); } } } |
请发表评论