首页 > 代码库 > C# 中的委托和事件
C# 中的委托和事件
C# 中的委托和事件
http://www.tracefact.net/CSharp-Programming/Delegates-and-Events-in-CSharp.aspx
/// <summary> /// 不好的设计 /// 后期增加语种需要增加改动3个地方:语种枚举、switch-case、方法 /// </summary> public class BadDesign { public enum Language { English, Chinese //add other language } public void GreetPeople(string name, Language lang) { switch (lang) { case Language.English: EnglishGreeting(name); break; case Language.Chinese: ChineseGreeting(name); break; //add other language } } public void EnglishGreeting(string name) { Console.WriteLine("Good Morning, " + name); } public void ChineseGreeting(string name) { Console.WriteLine("早上好, " + name); } //add language method } /// <summary> /// 相对较好的设计 /// 后期增加语种需要增加改动1个地方:语种方法 /// </summary> class GoodDesign_Delegate { public void GreetPeople(string name, GreetingDelegate MakeGreeting) { MakeGreeting(name); } public void EnglishGreeting(string name) { Console.WriteLine("Good Morning, " + name); } public void ChineseGreeting(string name) { Console.WriteLine("早上好, " + name); } //add language method } public delegate void GreetingDelegate(string name); class Program { static void Main(string[] args) { new BadDesign().GreetPeople("nlh", Delegate_Event.BadDesign.Language.Chinese); new BadDesign().GreetPeople("nlh", Delegate_Event.BadDesign.Language.English); new GoodDesign_Delegate().GreetPeople("nlh", new GoodDesign_Delegate().ChineseGreeting); new GoodDesign_Delegate().GreetPeople("nlh", new GoodDesign_Delegate().EnglishGreeting); Console.Read(); } }
C# 中的委托和事件
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。