一、委托
委托类似于函数指针,但函数指针只能引用静态方法,而委托既能引用静态方法,也能引用实例方法。
委托使用分三步:1、委托声明。2、委托实例化。3、委托调用。
二、事件
1、委托、实例化
Code
namespace TestEvent
{
public struct ALARM
{
public string name;
public string addr;
}
public delegate void AlarmEventHandler(ALARM xx);
public class Alarm
{
public event AlarmEventHandler OnAlarmEvent;
public void RaiseAlarm(ALARM mess)
{
if (OnAlarmEvent != null)
OnAlarmEvent(mess);
}
public void Test()
{
ALARM alarm = new ALARM();
alarm.addr = "beijing";
alarm.name = "yao";
for(int i=0;i<10;i++)
{
RaiseAlarm(alarm);
Thread.Sleep(2000);
}
}
}
}
2、事件调用
Code
namespace TestEvent
{
class Program
{
static void Main(string[] args)
{
Alarm alarm = new Alarm();
alarm.OnAlarmEvent+=new AlarmEventHandler(OnAlarm);
alarm.Test();
Console.ReadLine();
}
public static void OnAlarm(ALARM xx)
{
Console.WriteLine(xx.name);
Console.WriteLine(xx.addr);
}
}
}