C#委托

转自:http://www.cnblogs.com/ArmyShen/archive/2012/08/31/2664727.htmlhtml

委托是一个类,它定义了方法的类型,使得能够将方法看成另外一个方法的参数来进行传递,这种将方法动态地赋给参数的作法,能够避免在程序中大量使用if-else(switch)语句,同时使得程序具备更好的可扩展性。编程

使用委托能够将多个方法绑定到同一个委托变量上(一般称这个委托变量为:委托链),当调用此变量时,会依次调用全部绑定的方法;于此同时,也能够经过相似绑定的方式删除方法。函数

 

一个简单的委托例子post

复制代码
using System; using System.Collections; namespace Delegate { //用delegate关键字声明一个委托 //委托原型必须与预委托的方法具备相同的返回值和参数类型 delegate void LearnDelegate(string name); public class Test {
     //要进行委托的方法 static void LearnA(string name) { Console.WriteLine("小王在学" + name); }        static void LearnB(string name) { Console.WriteLine("小张在学" + name); } static void Main() { //建立委托实例,并把委托函数名看成参数传递给委托对象 LearnDelegate learn_A = new LearnDelegate(LearnA); LearnDelegate learn_B = new LearnDelegate(LearnB); //经过委托对象,给绑定的函数传递参数,其实如今的learn_A和learn_B就是learnA和learnB的函数别名 learn_A("C#"); learn_B("C++"); } } }
复制代码

 

委托链spa

复制代码
static void Main() {   //建立委托实例   LearnDelegate learn_A = new LearnDelegate(LearnA);   LearnDelegate learn_B = new LearnDelegate(LearnB);   //声明一个委托链,不须要实例化它   LearnDelegate DelegateLst;   //把委托对象直接相加并赋给委托链   DelegateLst = learn_A + learn_B;   //给委托链传值   DelegateLst("编程");   Console.WriteLine();   //一样,也能够对委托链中的委托对象进行添加和删除操做    DelegateLst -= learnA;//删除一个委托方法,这里使用DelegateLst -= Learn_A;效果是同样的,由于此时能够看做它是LearnA方法的一个别名   DelegateLst("编程");   Console.WriteLine();   DelegateLst += learnB;//添加一个委托方法,一样这里也可使用DelegateLst += Learn_B;   DelegateLst("编程"); }
复制代码

 

委托链的简化使用code

复制代码
using System; using System.Collections; namespace Delegate { //用delegate关键字声明一个委托 //委托原型必须与预委托的方法具备相同的返回值和参数类型 delegate void LearnDelegate(string name); public class Test { static void Main() { //声明一个委托链,赋null值 LearnDelegate DelegateLst = null; //下面这种形式实际上是匿名方法的一种应用 DelegateLst += delegate(string name) { Console.WriteLine("小王在学" + name); }; DelegateLst += delegate(string name) { Console.WriteLine("小张在学" + name); }; DelegateLst("编程"); } } }
复制代码

 

最后的一个例子htm

复制代码
using System; using System.Collections; namespace Delegate { //用delegate关键字声明一个委托 //委托原型必须与预委托的方法具备相同的返回值和参数类型 delegate void AnimalDelegate(string AnimalName); class Animal { public Animal() { } //要进行委托的方法 public void Miaow(string name) { Console.WriteLine( name + " 喵喵叫"); } //要进行委托的方法 public void Bark(string name) { Console.WriteLine(name + " 汪汪叫"); } //要进行委托的方法 public void Baa(string name) { Console.WriteLine(name + " 咩..."); } } public class MainFunc { static void choseAnimal(string name, AnimalDelegate delegateFun) { delegateFun(name); } static void Main() { /*AnimalDelegate cat = new AnimalDelegate(new Animal().Miaow); cat("猫咪"); AnimalDelegate dog = new AnimalDelegate(new Animal().Bark); dog("狗狗");*/ //上下的两种调用方式是等价的  choseAnimal("喵星人", new Animal().Miaow); choseAnimal("汪星人", new Animal().Bark); choseAnimal("喜洋洋", new Animal().Baa); } } }
复制代码
相关文章
相关标签/搜索