1. 什么是委托
委托是一种特殊的类型,这个类型可以赋值一个方法的引用。
private delegate void GetAstring(); //一个委托的结构,委托名是GetAstring,可以不合方法名一样
private void GetAstring()// 这个一个方法
2.如何使用 委托
class Program { private delegate string GetAstring(string a); static string SayWord(string a) { Console.WriteLine("这是说的话"+a); return a; } static void SayFirst() { Console.WriteLine("第一句话"); } static void SaySecond() { Console.WriteLine("这是第二句话"); } static void Main(string[] args) { 委托的调用 //GetAstring astring = SayWord;//定义一个变量 astring 接受函数名 //string str=astring("ni hao");//astring 相当于SayWord //Console.WriteLine(str); //Console.ReadKey(); //Action 和 Func 都是系统定义的委托 //方法1 //Func<string, string> aFunc = SayWord; //string a= aFunc("func"); //方法2 //Func<string, string> aFunc = SayWord; //string str = aFunc.Invoke("func"); //Console.WriteLine(str); //Console.ReadKey(); //Action接受没有 返回值的参数 //多播委托 //Action a = SayFirst; //a+=SaySecond; //Delegate[] delegates = a.GetInvocationList(); //foreach (Delegate de in delegates) //{ // de.DynamicInvoke(); //} //Console.ReadLine(); //匿名 方法 ->lambda 表达式 //Func<int,int> action = delegate(int a) //{ // Console.WriteLine("好像"+a); // return a; //}; //c# 3.0以后出现lambda表达式 Func<int, int> test = a => a + 1;// 第一个a是传入参数,第二个=> 函数体和返回值,当=>后只有一句话就会不用加{} }
2.事件
事件是一个委托提供了发布/订阅 机制,事件是属性类或者对象向其他通知事情的委托。事件:提供外部外部访问的接口,委托表示回调。public class Cat { private string Name; private string Color; public event Action CatCome; public Cat(string name,string color) { this.Name = name; this.Color = color; } public void CatComing() { Console.WriteLine("名字是{0}颜色是{1}的猫来了",Name,Color); if (CatCome != null) { CatCome(); } } }
事件只有使用+= 添加事件,不能自己调用,委托就可以调用,两者使用的方式也不一样。public class Mouse { private string name; private string color; public Mouse(string name,string color,Cat cat) { this.name = name; this.name = color; cat.CatCome += this.MouseRunnig; //把老鼠的方法注册到catcome中; } public void MouseRunnig() { Console.WriteLine("老鼠快跑"); } }