委托,Lambda,事件
2018-11-11 本文已影响0人
___________6a1d
委托
![](https://img.haomeiwen.com/i13648258/3921f531ae05c78a.png)
声明委托
![](https://img.haomeiwen.com/i13648258/2f6b3386f8f4befa.png)
Action和Func
![](https://img.haomeiwen.com/i13648258/46068fbad3e2664a.png)
Lambda
![](https://img.haomeiwen.com/i13648258/d4ea97797d3d7bb7.png)
![](https://img.haomeiwen.com/i13648258/0be4f9a7ff294178.png)
事件及事件的应用
![](https://img.haomeiwen.com/i13648258/f671251826884e42.png)
class Program
{
static void Main(string[] args)
{
Cat cat = new Cat("汤姆", 50);
Mouse mouse1 = new Mouse("杰瑞", 10,cat);
Mouse mouse2 = new Mouse("瑞士", 10,cat);
cat.Caught();
Console.ReadLine();
}
}
class Cat
{
string name;
int age;
public Cat(string name, int age)
{
this.name = name;
this.age = age;
}
public void Caught()
{
Console.WriteLine(name + "猫来抓老鼠了");
if (catCome != null)
catCome();
}
public event Action catCome;
}
class Mouse
{
string name;
int age;
public Mouse(string name, int age,Cat cat)
{
this.name = name;
this.age = age;
cat.catCome += Run;
}
public void Run()
{
Console.WriteLine(name + "快跑");
}
}
事件与委托的区别
事件不能再类的外部调用,可以在外部注册
委托可以在类的外部调用,可以在外部注册
![](https://img.haomeiwen.com/i13648258/a769338b2f08ccd6.png)