总之我觉得事件和委托不是那么好真正理解,委托原本很好理解,可是一旦事件和委托难分难解的时候,我总是有点迷糊,即使当时我看人家写的很明白,大概当时自己也明白了,可是事后一想,我又糊涂了。
于是,我自己也按我的理解写了一个委托和事件的小例子,大概是懂了,希望往后也不要再迷糊,假若又迷糊了,那就回来看看吧。
程序的意思是工人上班要外出,保安拦住了。

Code
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication3
{
/// <summary>
/// 定义WorkerEventArgs类是用于在事件发送器和事件接收器之间传递信息
/// </summary>
public class WorkerEventArgs :EventArgs
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
public WorkerEventArgs() : base() { }
}
/// <summary>
/// 定义工人类 工人类是发送器 发送器定义接收器要使用的委托以及相关事件成员
/// </summary>
public class Worker
{
public delegate void GoOutEventHandle(object sender,WorkerEventArgs e);
public static event GoOutEventHandle ProhibitOut;
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
public void GoOut()
{
Console.WriteLine("我要外去!");
WorkerEventArgs we = new WorkerEventArgs();
we.Name = this.Name;
OnGoOut(this,we);
}
public void OnGoOut(object sender,WorkerEventArgs e)
{
if (ProhibitOut != null)
{
ProhibitOut(sender,e);
}
}
}
/// <summary>
/// 事件接收类 接收器将事件处理程序注册到事件中
/// </summary>
public class Security
{
public Security()
{
Worker.ProhibitOut += new Worker.GoOutEventHandle(Prohibit);//注册事件ProhibitOut
}
public void Prohibit(object sender,WorkerEventArgs e)
{
Console.WriteLine(e.Name+",上班期间您不能外出!");
}
}
class Program
{
static void Main(string[] args)
{
Security st = new Security();
Worker wk = new Worker();
wk.Name = "aryang";
wk.GoOut();
Console.ReadKey();
}
}
}
于是,我自己也按我的理解写了一个委托和事件的小例子,大概是懂了,希望往后也不要再迷糊,假若又迷糊了,那就回来看看吧。
程序的意思是工人上班要外出,保安拦住了。


using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication3
{
/// <summary>
/// 定义WorkerEventArgs类是用于在事件发送器和事件接收器之间传递信息
/// </summary>
public class WorkerEventArgs :EventArgs
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
public WorkerEventArgs() : base() { }
}
/// <summary>
/// 定义工人类 工人类是发送器 发送器定义接收器要使用的委托以及相关事件成员
/// </summary>
public class Worker
{
public delegate void GoOutEventHandle(object sender,WorkerEventArgs e);
public static event GoOutEventHandle ProhibitOut;
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
public void GoOut()
{
Console.WriteLine("我要外去!");
WorkerEventArgs we = new WorkerEventArgs();
we.Name = this.Name;
OnGoOut(this,we);
}
public void OnGoOut(object sender,WorkerEventArgs e)
{
if (ProhibitOut != null)
{
ProhibitOut(sender,e);
}
}
}
/// <summary>
/// 事件接收类 接收器将事件处理程序注册到事件中
/// </summary>
public class Security
{
public Security()
{
Worker.ProhibitOut += new Worker.GoOutEventHandle(Prohibit);//注册事件ProhibitOut
}
public void Prohibit(object sender,WorkerEventArgs e)
{
Console.WriteLine(e.Name+",上班期间您不能外出!");
}
}
class Program
{
static void Main(string[] args)
{
Security st = new Security();
Worker wk = new Worker();
wk.Name = "aryang";
wk.GoOut();
Console.ReadKey();
}
}
}