using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 面试题案例 { class 委托 { public void 初级版() { int inputSelected = 1; while (inputSelected == 1) { Console.WriteLine("请输入名字"); string inputName = Console.ReadLine(); GreetPeople(inputName); Console.WriteLine("请选择 1:继续,2:退出"); inputSelected = int.Parse(Console.ReadLine()); } } public void 过渡版() { int inputSelected = 1; while (inputSelected == 1) { Console.WriteLine("请选择国家 1:美国人 2中国人"); string inputCountry = Console.ReadLine(); Console.WriteLine("请输入名字"); string inputName = Console.ReadLine(); if (inputCountry == "1") { GreetPeople(inputName, Language.Enlish); } else { GreetPeople(inputName, Language.Chinese); } Console.WriteLine("请选择 1:继续,2:退出"); inputSelected = int.Parse(Console.ReadLine()); } } public void 终极版() { int inputSelected = 1; while (inputSelected == 1) { Console.WriteLine("请选择国家 1:美国人 2中国人"); string inputCountry = Console.ReadLine(); Console.WriteLine("请输入名字"); string inputName = Console.ReadLine(); if (inputCountry == "1") { GreetPeople(inputName,EnlishGreeting); } else { GreetPeople(inputName, ChineseGreeting); } Console.WriteLine("请选择 1:继续,2:退出"); inputSelected = int.Parse(Console.ReadLine()); } } #region 什么是委托 public void GreetPeople(string name) { EnlishGreeting(name); } public void GreetPeople(string name, Language lang) { switch (lang) { case Language.Enlish: EnlishGreeting(name); break; case Language.Chinese: ChineseGreeting(name); break; } } public void EnlishGreeting(string name) { Console.WriteLine("GoodMorining " + name); Console.ReadKey(); } public void ChineseGreeting(string name) { Console.WriteLine("早上好 " + name); Console.ReadKey(); } #endregion public enum Language { Enlish, Chinese } public delegate void GreetingDelegate(string name); public void GreetPeople(string name,GreetingDelegate MakeGreeting) { MakeGreeting(name); } } }
使用
委托 weituo = new 委托(); Console.WriteLine("请选择使用的版本 1: 初级版,2:过渡板 3:终极版" ); string input_selected = Console.ReadLine(); int flag = 1; while (flag==1) { if (input_selected=="1") { weituo.初级版(); } else if (input_selected=="2") { weituo.过渡版(); } else if (input_selected == "3") { weituo.终极版(); } Console.WriteLine("1 :继续 2:退出"); flag = int.Parse( Console.ReadLine()); }