今天复习了一下C#委托与事件,顺便研究了一下自定义事件,写了下面的一个类
/*
public class ActionClass
{
public delegate void TestActionEventHandler(object sender, ActionCancelEventArgs e); public event TestActionEventHandler TestAction; public void Class_Load(object sender, ActionCancelEventArgs e)
{
if (sender != null)
TestAction(sender, e);
}
}
*/之后我有个疑惑,自定义事件在调用时,必须要手工增加类的实例.Class_Load这个方法,如:
ActionClass win = new ActionClass();
win.TestAction += new ActionClass.TestActionEventHandler(this.win_TestAction);
win.Class_Load(win,new ActionCancelEventArgs());但我使用winForm控件,拖一个Button在界面上,添加Click事件时,却不用手工再去调用Button里面的那个方法手工触发。为何这些控件里面不须手工触发?
/*
public class ActionClass
{
public delegate void TestActionEventHandler(object sender, ActionCancelEventArgs e); public event TestActionEventHandler TestAction; public void Class_Load(object sender, ActionCancelEventArgs e)
{
if (sender != null)
TestAction(sender, e);
}
}
*/之后我有个疑惑,自定义事件在调用时,必须要手工增加类的实例.Class_Load这个方法,如:
ActionClass win = new ActionClass();
win.TestAction += new ActionClass.TestActionEventHandler(this.win_TestAction);
win.Class_Load(win,new ActionCancelEventArgs());但我使用winForm控件,拖一个Button在界面上,添加Click事件时,却不用手工再去调用Button里面的那个方法手工触发。为何这些控件里面不须手工触发?
解决方案 »
- C#创建连接对象为什么要用using
- 装箱与解引用的问题
- ???求可以绑定数据的updown控件webform
- 关于使用ILOG Gantt for .NET 连接 数据库
- 请问这是什么写法?
- javascript:go(-1),别人告诉我这个可以返回上以页,但具体怎么写,请高手指教!!谢谢!
- 多显示器 扩展模式到复制模式的转换
- C#打包问题 打包flash
- 还是有错 net_lover(孟子E章) osborne(不知先生!) 帮忙啊。
- 开发端和客户端分辨率不同的时候,开发程序的烦恼。
- C#窗体可以加动态的图片么?
- 求助,c#调用Delphi的dll,有个参数为pbyte类型,请问c#中哪个类型与它对应
使用委托来实现的,需要你手动触发的
if (sender != null)
TestAction(sender, e);这句也有问题,你应判断TestAction事件是否为null.这个控件实际上也是有触发的,不过他们是写在基类里了,注册处理器也许在其他的部份类中了。
并且C#的规范是以On打头,如:OnClick,OnLoad();这些事件触发器大多是protected的虚方法;
如:
public class XX
{
public event EventHandler<EventArgs> MyEvent;
protected virtual void OnMyEvent(EventArgs e)
{
if(MyEvent!=null)
{
MyEvent(this,e);
}
}
}
内部触发其实也很简单的,比如:我有一个文件管理类,当我打开一个文件成功后,就触发一个文件打开事件:public class FileManager
{
//这个就是事件了,使用默认的事件参数,当然你可以从EventArgs继承并实现自己的事件参数类
public event EventHandler<EventArgs> FileOpened;//这个就是保护的虚方法,在这里我叫它事件触发器,因为这个方法可以触发挂接到FileOpened事件上的所有事件;
protected virtual void OnFileOpened(EventArgs e)
{
EventHandler<EventArgs> eh=FileOpened;
if(eh!=null)
{
eh(this,e);
}
}
//好,接下来我写一个打开文件的方法,当文件打开成功则触发FileOPened事件
public Boolean OPenFile()
{
String filename="c:\1.txt";
//.....当文件打开成功时,执行下面的代码
OnFileOpened(EventArgs.Empty);//这里就触发了类中的事件:FileOpened;
}
}自己体会一下,然后写写代码,估计就掌握了,其实C#中的事件还是很简单的;