事件
委托与事件的区别:事件在哪个类定义,就要在哪个类发布,委托哪里都能发布
using System;
namespace _008事件
{
class Program
{
public delegate void GetNum();//定义委托
public static event GetNum Get;
//定义事件,静态方便调用
static void Main(string[] args)
{
People people = new People();
//要先创建对象,否则事件不能发布
Get();//发布事件
}
}
public class People
{
string name;
int age;
public string Name { get => name; set => name = value; }
public int Age { get => age; set => age = value; }
public People()//构造函数或者说是初始化创建对象
{
Program.Get += Eat;
//要通过类调用事件,静态直接调用,不用创建对象
Program.Get += Drink;
}
public void Eat()
{
Console.WriteLine("人会吃");
}
public void Drink()
{
Console.WriteLine("人会喝");
}
}
}
猫和老鼠观察者模式
方法1:委托、猫监听老鼠
using System;
namespace _009猫和老鼠观察者模式
{
class Program
{
static void Main(string[] args)
{
Cat cat = new Cat("红色");
cat.CatCall();
Mouse mouse1 = new Mouse("blue");
Cat.Call call = mouse1.Run;//调用委托创建对象且传递方法
Mouse mouse2 = new Mouse("red");
call+= mouse2.Run;
Mouse mouse3 = new Mouse("yellow");
call += mouse3.Run;
call();//发布委托
}
}
class Cat
{
public delegate void Call();//定义委托
string color;
public string Color { get => color; set => color = value; }
public Cat(string c)
{
this.color = c;
}
public void CatCall()
{
Console.WriteLine(this.color+"的猫叫了");
}
}
class Mouse
{
string color;
public string Color { get => color; set => color = value; }
public Mouse(string c)
{
this.color = c;
}
public void Run()
{
Console.WriteLine(this.color+"的老鼠跑了");
}
}
}
方法2:事件、老鼠监听猫
using System;
namespace _009猫和老鼠观察者模式
{
class Program
{
static void Main(string[] args)
{
Cat cat = new Cat("红色");//先创建对象,再发布事件
Mouse mouse1 = new Mouse("blue",cat);
Mouse mouse2 = new Mouse("red",cat);
Mouse mouse3 = new Mouse("yellow",cat);
cat.CatCall();
}
}
class Cat
{
public delegate void Call();//定义委托
public event Call Listen;//定义事件
string color;
public string Color { get => color; set => color = value; }
public Cat(string c)
{
this.color = c;
}
public void CatCall()
{
Console.WriteLine(this.color+"的猫叫了");
Listen();//发布事件
}
}
class Mouse
{
string color;
public string Color { get => color; set => color = value; }
public Mouse(string c,Cat cat)
{
this.color = c;
cat.Listen += Run;
}
public void Run()
{
Console.WriteLine(this.color+"的老鼠跑了");
}
}
}