- 事件基于委托存在,事件是类的成员
- 事件不能在类外调用,虽然我们可以在类中声明事件为public,但实际编译代码时永远都是private,并且是private的委托(事件的本质就是委托)
- 定义事件处理方法,它与delegate对象具有相同的参数和返回值类型
- 定义事件时,发生者首先要定义委托,然后根据委托定义事件:
public delegate void SayHello(string name);
public event SayHello hello;
- 注册事件:
public void ToHelloAmerican(string name)
{
Console.WriteLine(name+",Welcome To American");
}
public void ToHelloChinese(string name)
{
Console.WriteLine(name + ",欢迎来中国");
}
static void Main(string[] args)
{
Hello h = new Hello();
h.hello += h.ToHelloAmerican;
h.hello += h.ToHelloChinese;
h.ToHello("Selinda");
Console.ReadKey();
}
- 触发事件:事件只能被所属的类调用,可以通过其他类向事件注册方法
public void ToHello(string name)
{
hello(name);
}
-----------------------------------------------------------------------------------------------
源代码如下:(类外注册事件)
public delegate void SayHello(string name);
class Hello
{
public event SayHello hello;
public void ToHello(string name)
{
hello(name);
}
public void ToHelloAmerican(string name)
{
Console.WriteLine(name+",Welcome To American");
}
public void ToHelloChinese(string name)
{
Console.WriteLine(name + ",欢迎来中国");
}
}
class Program
{
static void Main(string[] args)
{
Hello h = new Hello();
h.hello += h.ToHelloAmerican;
h.hello += h.ToHelloChinese;
h.ToHello("Selinda");
Console.ReadKey();
}
}
-----------------------------------------观察者模式------------------------------------------
- Observer设计模式是为了定义对象间的一种一对多的依赖关系,以便于当一个对象的状态改变时,其他依赖于它的对象会被自动告知并更新。Observer模式是一种松耦合的设计模式。
- Observer设计模式中主要包括两类对象:观察者、被观察对象。
- 以下代码:观察者(报警器、显示频)、被观察对象(温度)
public delegate void BoilEventHandler(int temperature);
class BoilWater
{
public event BoilEventHandler Boil;
public int temperature = 0;
public void OnBoilWater()
{
for (int i = 0; i < 101; i++)
{
temperature = i;
if (temperature > 95&&Boil!=null)
{
Boil(temperature);
}
}
}
public void Ring(int tem)
{
Console.WriteLine("报警器:"+tem);
}
public void Show(int tem)
{
Console.WriteLine("显示器:"+tem);
}
}
class Program
{
static void Main(string[] args)
{
BoilWater h = new BoilWater();
h.Boil += h.Ring;
h.Boil += h.Show;
h.OnBoilWater();
Console.ReadKey();
}
}
- 委托类型的名称都应该以EventHandler结束。
- 委托的原型定义:有一个void返回值,并接受两个输入参数:一个Object 类型(观察者),一个 EventArgs类型(或继承自EventArgs,被观察对象)。
- 事件的命名为 委托去掉 EventHandler之后剩余的部分。
- 继承自EventArgs的类型应该以EventArgs结尾。