注解:本文摘自網絡
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());
}
}
事件設定
作為快捷指南,可以根據這個來做。