委托和事件这两个概念是完全配合的。委托仅仅是函数指针,那就是说,它能够引用函数,通过传递地址的机制完成。委托是一个类,当你对它实例化时,要提供一个引用函数,将其作为它构造函数的参数。
using System;
class TestClass
{
static void Main(string[] args)
{
EventClass myEventClass = new EventClass();
myEventClass.CustomEvent += new EventClass.CustomEventHandler(CustomEvent1); // 关联事件句柄;
myEventClass.CustomEvent += new EventClass.CustomEventHandler(CustomEvent2);
//这里会将所有关联的函数一直执行
myEventClass.InvokeEvent();
//删除一个实践CustomEvent2关联
myEventClass.CustomEvent -= new EventClass.CustomEventHandler(CustomEvent2);
myEventClass.InvokeEvent();
//又增加一个关联
myEventClass.Load += new EventClass.CustomEventHandler(Load1);
myEventClass.onLoad();
Console.Read();
}
private static void CustomEvent1(object sender, EventArgs e)
{
Console.WriteLine("Fire Event 1");
}
private static void CustomEvent2(object sender, EventArgs e)
{
Console.WriteLine("Fire Event 2");
}
private static void Load1(object sender, EventArgs e)
{
Console.WriteLine("Current background color is {0}. Please input:", System.Console.BackgroundColor.ToString());
}
}
public class EventClass
{
public delegate void CustomEventHandler(object sender, EventArgs e);//首先定义一个委托类型的对象CustomEventHandle
//用delegate数据类型声明事件,要用event关键字,这里定义了两个字件;
//用于建立事件关联
public event CustomEventHandler CustomEvent;
//用于建立事件关联
public event CustomEventHandler Load;
public void InvokeEvent()
{
CustomEvent(this, EventArgs.Empty);
}
public void onLoad()
{
Console.BackgroundColor = ConsoleColor.Red;
Load(this, EventArgs.Empty);
string s = Console.ReadLine();
if (s != "yuping")
{
Console.WriteLine("You must type 'yuping' for change it !");
}
else
{
Console.BackgroundColor = System.ConsoleColor.Black;
Console.Clear();
}
}
}