delegate委托是存有对某个方法引用的一种引用类型变量。引用可在运行时被改变
什么情况下使用委托
a)当使用时间触发模式时
b) 当需要封装静态方法时
c)当调用方不需要访问实现该方法对象的其它属性,方法或接口时
d)当需要方便的组合时
e)当类可能需要该方法的多个实现时
using System; namespace 编码练习 { public enum Greeting { Hello, Goodbye } class Program { public static void Hello(string s) { Console.WriteLine(" Hello, {0}!", s); // do something (hug or shake hand...) } public static void Goodbye(string s) { Console.WriteLine(" Goodbye, {0}!", s); // do something (hug or wave hand...) } static void MakeGreeting(string name, Greeting greeting) { switch (greeting) { case Greeting.Hello: Hello(name); break; case Greeting.Goodbye: Goodbye(name); break; } } static void Main(string[] args) { MakeGreeting("May", Greeting.Hello); MakeGreeting("April", Greeting.Goodbye); } } }
using System; using System.Collections.Generic; namespace 编码练习 { //使用委托后的代码 delegate void GreetingDelegate(string s); //声明委托,定义Greeting方法的类 class Program { public static void Hello(string s) { Console.WriteLine(" Hello, {0}!", s); // do something (hug or shake hand...) } public static void Goodbye(string s) { Console.WriteLine(" Goodbye, {0}!", s); // do something (hug or wave hand...) } static void MakeGreeting(string name, GreetingDelegate d) { d(name); } static void Main(string[] args) { GreetingDelegate d1 = Hello; //定义委托的一个对象(将方法绑定到委托) GreetingDelegate d2 = Goodbye; //定义委托的另一个对象 MakeGreeting("May", d1); MakeGreeting("April", d2); } } }