事件对我这个从C转到C#的人来说,算上新鲜,虽然VB里也有事件,不过C#里的又有所不同。
今天看《C#高级编程》的事件部分,动手做做书上的例子,才算是略有理解,修改下书上的例子,以便简单容易理解。代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Event
{
public delegate void ActionEventHandler(object sender, EventArgs ev);//声明委托
public partial class Form1 : Form
{
public static event ActionEventHandler Action;//声明事件
public Form1()
{
Action += new ActionEventHandler(Form1_Action);//注册事件
InitializeComponent();
}
private void Form1_Action(object sender,EventArgs ev)//处理事件
{
DateTime tm = DateTime.Now;
if (tm.Second < 30)
{
labelControl1.Text = "The time is" + tm.ToLongTimeString();
}
else
labelControl1.Text = "Wasn't the right time";
}
protected void OnAction(object sender, EventArgs ev)//监听事件
{
if (Action != null)
Action(sender, ev);
}
private void simpleButton1_Click(object sender, EventArgs e)//触发事件
{
OnAction(this, e);
}
}
}

浙公网安备 33010602011771号