委托與事件
之前開發workflow需要寫委託與事件
沒有好好研究=.=
看了書作個小小練習順便記憶
物件定義
using System.Collections.Generic;
using System.Text;
namespace DesignModelTest.其它
{
/// <summary>
/// 買方付錢事件
/// </summary>
public class BuyerPayEventArgs : EventArgs
{
private string _buyerName;
public string buyerName
{
get{ return _buyerName;}
set{ _buyerName = value;}
}
}
class Buyer
{
private string _buyerName;
public Buyer(string name)
{
this._buyerName = name;
}
public delegate void BuyerPayEventHandler(object sender, BuyerPayEventArgs args);
public event BuyerPayEventHandler BuyerPay;
/// <summary>
/// 付錢.
/// </summary>
public void Pay()
{
Console.WriteLine("我是{0}", this._buyerName);
//觸發事件
if (BuyerPay != null)
{
BuyerPayEventArgs e = new BuyerPayEventArgs();
e.buyerName = this._buyerName;
//記得要丢參數及觸發
BuyerPay(this, e);
}
}
}
class Seller
{
private string _sellerName;
public Seller(string name)
{
this._sellerName = name;
}
/// <summary>
/// 賣商品.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="args">The <see cref="DesignModelTest.其它.BuyerPayEventArgs"/> instance containing the event data.</param>
public void Sell(object sender, BuyerPayEventArgs args)
{
Console.WriteLine(args.buyerName+" 付錢 , "+this._sellerName+" 賣東西");
}
}
}
執行程式碼
DesignModelTest.其它.Buyer buyer = new DesignModelTest.其它.Buyer("買方一");
DesignModelTest.其它.Seller seller1 = new DesignModelTest.其它.Seller("賣方一");
DesignModelTest.其它.Seller seller2 = new DesignModelTest.其它.Seller("賣方二");
//登記事件
buyer.BuyerPay +=new DesignModelTest.其它.Buyer.BuyerPayEventHandler(seller1.Sell);
buyer.BuyerPay += new DesignModelTest.其它.Buyer.BuyerPayEventHandler(seller2.Sell);
buyer.Pay();
Console.Read();
#endregion