例子
FileWatch.cs内容:
//FileWatch.cs内容:
using System;
using System.Collections.Generic;
using System.Linq;
namespace WindowsFormsEventTest
{
// 1、委托 (指向函数的指针 类型)
public delegate void FileChangedEventHandler(object sender, MyEventArgs e);
class FileWatch
{
//2、事件 (指向函数的指针变量 ——FileChangedEvent)
public event FileChangedEventHandler FileChangedEvent;
//3、触发事件的方法
public virtual void OnFileChange(MyEventArgs e)
{
if (FileChangedEvent != null)
{
FileChangedEvent(this, e);
}
}
}
}
Form1.cs文件内容如下:
using System;
using System.Windows.Forms;
namespace WindowsFormsEventTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
FileWatch EventSource = new FileWatch();//定义对象
EventSource.FileChangedEvent += new FileChangedEventHandler(FileChangeHandle);//注册事件(为指针赋值) +=
EventSource.FileChangedEvent += new FileChangedEventHandler(FileChangeHandle2);// 注册事件(为指针赋值)
EventSource.OnFileChange(e);
for (int i= 0; i < 500000000; ++i)
{
}
EventSource.OnFileChange(e);
for (int i = 0; i < 500000000; ++i)
{
}
EventSource.OnFileChange(e);
}
public void FileChangeHandle(object obj,MyEventArgs e)
{
listBox1.Items.Add(DateTime.Now.ToString() + " : 文件发生改变." +"Message:"+e.Info);
}
public void FileChangeHandle2(object obj, MyEventArgs e)
{
listBox2.Items.Add(DateTime.Now.ToString() + " : 文件发生改变." + "Message:" + e.Info);
}
}
}