C#委托的详细使用
代码如下:
public delegate void GreetingDelegate(string name);//定义委托,它定义了可以代表方法的类型 class Program { public static void EnglishGreeting(string name) { Console.WriteLine("Moring,"+name); } public static void ChineseGreeting(string name) { Console.WriteLine("早上好,"+name); } //注意此方法,他接收一个GreetingDelegate类型的方法作为参数 public static void GreetingPeople(string name,GreetingDelegate MakeGreeting) { MakeGreeting(name); } static void Main(string[] args) { //版本1 //GreetingPeople("Jake", EnglishGreeting);//英文问好 //GreetingPeople("王旭", ChineseGreeting);//中文问好 //版本2 //string name1, name2; //name1 = "Jack"; //name2 = "王旭"; //GreetingPeople(name1,EnglishGreeting); //GreetingPeople(name2,ChineseGreeting); //版本3 //GreetingDelegate delegate1, delegate2; //delegate1 = EnglishGreeting; //delegate2 = ChineseGreeting; //GreetingPeople("Jack",delegate1); //GreetingPeople("王旭",delegate2); //版本4 /* 注意:这里第一次使用"="是赋值的语法,第二次使用"+="是绑定的语法("-="取消绑定),如果第一次就使用"+="将会出现"使用了未赋值的局部变量"的编译错误 */ //GreetingDelegate delegate1; //delegate1 = EnglishGreeting;//先给委托类型的变量赋值 //delegate1 += ChineseGreeting;//在给此委托变量绑定一个值 //GreetingPeople("Jack",delegate1);//将先后调用EnglishGreeting和ChineseGreeting方法 //版本5 //GreetingDelegate delegate1; //delegate1 = EnglishGreeting; //delegate1 += ChineseGreeting; //delegate1("Jack"); //版本6 //GreetingDelegate delegate1 = new GreetingDelegate(EnglishGreeting); //delegate1 += ChineseGreeting; //delegate1("Jack"); //版本7 GreetingDelegate delegate1 = new GreetingDelegate(EnglishGreeting); delegate1 += ChineseGreeting; //将先后调用EnglishGreeting和ChineseGreeting方法 GreetingPeople("Jack",delegate1); delegate1 -= EnglishGreeting;//取消对EnglishGreeting方法的绑定 GreetingPeople("王旭",delegate1);//只显示ChineseGreeting方法 Console.ReadLine(); } }