C# 自訂帶自訂參數的事件方法
C# 自訂帶自訂參數的事件 需要經過以下幾個步驟:
1、自訂事件參數 :要實現自訂參數的事件,首先要自訂事件參數。該參數是個類。繼承自EventArgs。
2、聲明委託用於事件
3、聲明事件
4、定義事件觸發 :事件定義後,要有個觸發事件的動作。
以上基本上完成了自訂事件。不過還缺事件調用,請看下邊兩個步驟。
5、事件觸發
6、自己編寫事件的處理 :事件觸發後。要處理事件。
實現:
假設有個列印對象,需要給它自訂一個列印事件。事件參數中傳入列印的份數。在程式載入時,調用列印對象,並通過自訂列印參數,實現列印。
代碼如下,此代碼是在WinForm下編寫。
//列印對象
public class CustomPrint
{
/// <summary>
///
1、定義事件參數
/// </summary>
public class CustomPrintArgument : EventArgs
{
private int copies;
public CustomPrintArgument(int numberOfCopies)
{
this.copies = numberOfCopies;
}
public int Copies
{
get { return this.copies; }
}
}
/// <summary>
/// 2、聲明事件的委託
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public delegate void CustomPrintHandler(object sender, CustomPrintArgument e);
/// <summary>
/// 3、聲明事件
/// </summary>
public event CustomPrintHandler CustomPrintEvent;
/// <summary>
/// 4、定義觸發事件
/// </summary>
/// <param name="copyies">份數</param>
public void RaisePrint(int copyies)
{
CustomPrintArgument e = new CustomPrintArgument(copyies);
CustomPrintEvent(this, e);
}
}
/// <summary>
/// WinForm 建構函式
/// </summary>
public Form1()
{
InitializeComponent();
PrintCustom();
}
/// <summary>
/// 列印方法
/// </summary>
private void PrintCustom()
{
//執行個體對象
CustomPrint cp = new CustomPrint();
//添加事件
cp.CustomPrintEvent += new CustomPrint.CustomPrintHandler(cp_CustomPrintEvent);
//5、觸發事件
cp.RaisePrint(10);
}
//6、事件處理
void cp_CustomPrintEvent(object sender, CustomPrint.CustomPrintArgument e)
{
int copies = e.Copies;
MessageBox.Show(copies.ToString());
}
}
運行程式,在快顯視窗中會顯示10。