事件一般写的不是很多,多用在自定义控件等地方。又很容易遗忘,一般分以下几个步骤。 定义事件的标准模式如下(参考了.net框架设计一书)
1.构造一个静态只读对象标识事件
protected static readonly object clickEvent;
2.为事件定义一个继承自EvevtArgs的类型,用于保持传递给事件接受者的附加信息。如果没什么特别的信息的话,那我们用框架里的System.EventArgs类型就可以了。
public class CustomEventArgs:EventArgs{}
3.定义一个委托类型,指定事件触发时被调用的方法原形
public delegate void Gate_Click(string clickName);
4定义一个受保护的实例字段,可以引用一个集合来管理一组事件事件/委托对。一般可以使用System.ComponentMoedl.EventHandlerList类型。所以使用Control的Events类就可以了。
5为事件定义访问器的方法用于集合上添加/移除委托实例
public event Gate_Click ClickEvent
{
add
{
Events.AddHandler(clickEvent,value);
}
remove
{
Events.RemoveHandler(clickEvent,value);
}
}
6定义一个事件激发时所调用的方法,再使用委托调用所关联的方法。
protected void FireEvent(string str)
{
Gate_Click handler = (Gate_Click)Events[clickEvent];
if(handler != null)
handler(str);
}
7触发事件
private void invokeEvent(object sender,EventArgs e)
{
FireEvent("str");
}
好了。至此一个事件就已经完成了。但control.Events使用线性搜索所以量大时效率比较低,而且不保证线性安全。如果有需要可以自行编写Events类。
1.构造一个静态只读对象标识事件
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
5为事件定义访问器的方法用于集合上添加/移除委托实例
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockEnd.gif)