C# 中的委托和事件
Posted nlh774
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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# 中的委托和事件的主要内容,如果未能解决你的问题,请参考以下文章