TestEvent.cs
using System;
namespace ConsoleApplication2
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class TestEvent
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: 在此处添加代码以启动应用程序
//
TestEvent c = new TestEvent();
c.Test();
}
public void Test()
{
ChangeNumber number = new ChangeNumber();
number.BigEvent += new ChangeNumber.ChangeHandler(this.Big);
number.SmallEvent += new ChangeNumber.ChangeHandler(this.Small);
number.EqualEvent += new ChangeNumber.ChangeHandler(this.Equal);
number.Number = 1; //运行之前Number=0;
number.Number = 1; //运行之前Number=1;
number.Number = 0; //运行之前Number=1;
}
public void Big()
{
Console.WriteLine("big");
}
public void Small()
{
Console.WriteLine("small");
}
public void Equal()
{
Console.WriteLine("equal");
}
}
}
ChangeNumber.cs
using System;
namespace ConsoleApplication2
{
/// <summary>
/// Class2 的摘要说明。
/// </summary>
public class ChangeNumber
{
public delegate void ChangeHandler();
public event ChangeHandler BigEvent;
public event ChangeHandler SmallEvent;
public event ChangeHandler EqualEvent;
public ChangeNumber()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
private int m_number = 0;
public int Number
{
set
{
if(value > this.m_number)
{
BigEvent(); //这时最好先判断一下BigEvent是不是为null
}
else if(value < this.m_number)
{
SmallEvent();
}
else
{
EqualEvent();
}
m_number = value;
}
}
}
}