委托是方法的调用,可以更加灵活
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace _13 { public class ClassPeople { public void SayChinese(string name) { Console.WriteLine("你好," + name); } public void SayEnglish(string name) { Console.WriteLine("Hello," + name); } public enum Language { English, Chinese } public void DoWork(string name, Language lang) { switch (lang) { case Language.English: SayEnglish(name); break; case Language.Chinese: SayChinese(name); break; } } } class Program { static void Main(string[] args) { ClassPeople cp = new ClassPeople(); cp.DoWork("李天平", ClassPeople.Language.Chinese); cp.DoWork("litianping", ClassPeople.Language.English); System.Console.ReadLine(); } } }
上述代码,根据传进来的语言枚举值和名字符串来输出相应语言的问候语,不过,这个方法的可扩展性太差了,如果以后我们需要再添加韩文版,日文版,就不得不反复修改枚举和Dowork()方法,以适应新的需求。
使用委托可以解决优化此类问题。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace _14 { public delegate void SayDelegate(string name); public class ClassPeople { public void SayChinese(string name) { Console.WriteLine("你好," + name); } public void SayEnglish(string name) { Console.WriteLine("Hello," + name); } //注意此方法,它接受一个SayDelegate类型的方法作为参数 public void DoWork(string name, SayDelegate MakeSay) { MakeSay(name); } } class Program { static void Main(string[] args) { ClassPeople cp = new ClassPeople(); cp.DoWork("李天平", cp.SayChinese); cp.DoWork("litianping", cp.SayEnglish); System.Console.ReadLine(); } } }
优化化,我们要加一种问候语,只要新增一个方法就可以了。
参考地址:https://www.cnblogs.com/eagle1986/archive/2012/02/21/2360748.html