c#中delegate被称作是“委托”,类似c++中的函数指针,委托也可以指向一个函数,但是不同的是,委托可以被理解为一个列表,里面的元素是一系列返回类型和参数表都相同的函数,之后就可以像使用变量一样使用函数。system中有很多预先定义好的委托类型可以直接被调用,比如eventhandler就是事件的委托类型。
事件是一种委托变量,里面可以接受在不同情况下注册的事件,循环调用里面的每一个函数,比如下面的例子中在main中和在people类中分别注册了boiled事件,分别给他写了触发时的方法,而在boil原型中则说明了Boiled事件在什么条件下会被触发。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace SayHello
{
public class Boiler
{
private int _temperature = 24; //record the temperature of the water
Timer t = null; //timer类需要using System.Threading,在最开始的时候需要初始化为null
public event EventHandler Boiled; //事件变量的声明
public event EventHandler temperatureChanged;
public int temprature //Boiler的temperature属性
{
get
{
return _temperature;
}
private set
{
_temperature = value;
}
}
public void beginBoilWater() //timer的四个参数,第一个是一个参数类型为object的函数,表示的是每次计时器被调用时的操作,第二个参数是传给第一个函数的变量,第三个参数是指timer从new到第一次生效所经历的时间,第四个参数是timer的调用周期
{
t = new Timer(Boil, null, 0, 1000);
}
public void Boil(object o)
{
_temperature += 10;
if(temperatureChanged != null) //事件被触发之前需要检查它是否被注册,接下来的就是事件的触发条件
{
temperatureChanged(this, new EventArgs());
}
if(_temperature > 100)
{
if(Boiled != null)
{
Boiled(this, new EventArgs());
}
t.Dispose(); //timer被销毁
t = null;
}
}
}
public class people //people就是对事件的外部观察者
{
private Boiler b = new Boiler();
public Boiler Boiler
{
get
{
return b;
}
}
public void boilWater() //先注册事件,后面表示事件被触发时的操作
{
b.Boiled += B_Boiled;
b.temperatureChanged += B_temperatureChanged;
b.beginBoilWater();
}
private void B_temperatureChanged(object sender, EventArgs e)
{
Console.WriteLine("{0}", b.temprature);
}
private void B_Boiled(object sender, EventArgs e)
{
Console.WriteLine("Completed!");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SayHello
{
class Program
{
private static bool canExit = false;
static int Main(string[] args)
{
people p = new people();
p.boilWater();
p.Boiler.Boiled += Boiler_Boiled;
while(canExit == false)
{
;
}
return 0;
}
private static void Boiler_Boiled(object sender, EventArgs e)
{
canExit = true;
}
}
}