C# 使用委托模型 来实现事件,事件的处理方法不必在将生成事件的类中定义,需要做的事情就是把事件源和事件处理程序结合起来,使用事件处理委托,简称事件委托可以定义为生成事件的类的一个成员,事件委托为多播的。
事件委托的形式
public delegate void MouseHandler(object source , EventArgs e)
object souce 为事件源(表示发生事件的来源,比如 button)
EventArgs :System.EventArgs类的实例或者派生类的实例,它包含事件的另外信息。
.NET Framework 定义了大量的事件处理委托
如:public delegate void KeyEventHanlder(boject souce ,KeyEventArgs args)
如:public delegate void MouseEventHanlder(boject souce ,MouseEventArgs args)
..........................................................................................................................................................................................................
用户自定义事件委托(只为说明下事件委托运行原理)
public delegate void NameEventHandler (object souce,NewEventArgs e)
必须自己定义 NewEventArgs类,NewEventArgs 为System.EventArgs的派生类
创建事件委托的实例 不用new 关键词,使用 envet关键字 pubic event NameEventHandler namehandler;
触发事件
1)把事件委托的一个实例定义为类的成员
比如button的Click事件 把事件委托的一个实例成员定义到button类中
2)确定何时生成事件代码
3)定义生成提供事件的EventArgs对象代码
Demo
public class NameListEventArgs:EventArgs
{
public string name;
public int count;
public NameListEventArgs(string name,int count)
{
this.name=name;
this.count=count;
}
public string Name
{
get{ return name;}
set{name=value}
}
public int Cout
{
get{return count;}
set{count=value;}
}
}
public class Namelist //相当于事件源类,如发生单击事件的button类
{
ArrayList list;
public event NameListEventhandler nameListEvent;
pubic Namelist()
{
list =new ArrayList();
}
public void Add (string name)
{
list.Add(name);
if(nameListEvent !=null)
{
nameListEvent (this ,new NameListEventArgs(name,listCount) ); //new NameListEventArgs(name,listCount) 为EventArgs的派生类的实例
}
}
}
namespace Demo
{
public class TestDemo
{
private void button_Click(object sender ,EventArgs e)
{
NameList name =new NameList();
name.nameListEvent+=new NameListEventHandler(NewName);
name.nameListEvent+=new NameListEventHandler(CurrentCount);
name.Add("Msdn");
name.Add("Webcast");
}
public static void NewName(object souce,NameListEventArgs e)
{
console.write("sssssss");
}
public static void CurrentCount(object souce,NameListEventArgs e)
{
console.write("qqqqq");
}
}
}
原文地址:http://www.cnblogs.com/871735097-/p/3826248.html