// Time:2010-01-05 16:41 星期二 中国广州天河,今晚天气即将转冷!
// 示例代码显示了:一个完整的事件处理程序示例
using System;
namespace Donis.CSharpBook{
public class Start
{
public static void Main()
{
Bank account = new Bank();
account.NSF += NSFHandler;
account.Deposit(500); // 存入
account.WithDraw(750);// 透支
}
public static void NSFHandler(object o,BankEventArgs e)
{
Console.WriteLine("无法透支!");
Console.WriteLine("可用余额:{0} RMB",e.Banlance);
Console.WriteLine("需透支余额:{0} RMB",e.Transaction);
}
}
// 用于定义事件的委托
public delegate void OverDraw(object o,BankEventArgs e);
public class Bank
{
public event OverDraw NSF;// none sufficient funds
private decimal propBanlance = 0;
public decimal Banlance
{
get
{
return this.propBanlance;
}
}
public decimal Deposit(decimal amountDeposit)
{
propBanlance += amountDeposit;
return propBanlance;
}
public decimal WithDraw(decimal amountWithDraw)
{
decimal newBalance = propBanlance - amountWithDraw;
if(newBalance <0)
{
if(NSF != null)
{
// 引发事件,使订阅者处理.
BankEventArgs args = new BankEventArgs(this.Banlance,amountWithDraw);
NSF(this,args);
//NSF.Invoke(this,args);
}
}
// 以下这句同时执行赋值并返回.newBalance
return propBanlance = newBalance;
}
}
public class BankEventArgs:EventArgs
{
private decimal propBalance;
public decimal propTransaction;
// 构造函数
public BankEventArgs(decimal amountBalance,decimal amountTransaction)
{
propBalance = amountBalance;
propTransaction = amountTransaction;
}
public decimal Banlance
{
get
{
return this.propBalance;
}
}
public decimal Transaction
{
get
{
return this.propTransaction;
}
}
}
}
运行效果: