1. 使用委托来解决逻辑分离,解除耦合
2.委托的高级应用实例
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MyDelegateDemo { public delegate void SayHelloHandler(string name);//1.委托的声明 public class Greeting { public static void SayHello(string name, PeopleType type) { if (type == PeopleType.Chinese) { Console.WriteLine("早上好,{0}", name); } else if (type == PeopleType.American) { Console.WriteLine("Good morning,{0}", name); } } /// <summary> /// 委托,逻辑分离,解除耦合 /// </summary> /// <param name="name"></param> /// <param name="sayHello">委托的实例</param> public static void SayHelloDelegate(string name, SayHelloHandler sayHello) { sayHello(name);//委托的调用 } public static void SayHelloChinese(string name) { Console.WriteLine("早上好,{0}", name); } public static void SayHelloAmerican(string name) { Console.WriteLine("Good morning,{0}", name); } } public enum PeopleType { Chinese, American } } using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MyDelegateDemo { class Program { //采用委托易于扩展,对扩展开放,对修改封闭的原则 static void Main(string[] args) { Console.WriteLine("欢迎来到流星小子博客学习"); Greeting.SayHello("流星小子", PeopleType.Chinese); Greeting.SayHello("Meter", PeopleType.American); //委托的实例化 SayHelloHandler sayHelloHandler = new SayHelloHandler(Greeting.SayHelloChinese); Greeting.SayHelloDelegate("流星小子", sayHelloHandler); SayHelloHandler sayHello = new SayHelloHandler(Greeting.SayHelloAmerican); Greeting.SayHelloDelegate("Meter", sayHello); //sayHelloHandler -= Greeting.SayHelloChinese; //sayHelloHandler += Greeting.SayHelloAmerican; //Greeting.SayHelloDelegate("MeterName", sayHelloHandler); //sayHelloHandler -= Greeting.SayHelloAmerican; Console.Read(); } } }