自訂
事件
it
using System;
delegate viod CharEventHandler(object sender, CharEventArgs e);
自訂了一個觸發事件的參數
public class CharEventArgs EventArgs
{
public char CurrChar;
public CharEventArgs(char CurrChar)
{
this.CurrChar = CurrChar;
}
}
class CharChecker
{
char curr_char;
public event CharEventHandler CharTest;
public char Curr_Char
{
get{return curr_char;}
set
{
if(CharTest!=null)
{
CharEventArgs myeven=new CharEventArgs(value);
CharTest(this,myeven); 在這裡觸發事件
curr_char=myeven.CurrChar
}
}
}
}
class AppEvent
{
static void Main()
{
CharChecker chartester=new CharChecker();
chartester.CharTest+=new CharEventHandler(Change_X);觸發事件Chartest時, 綁定到Change_X函數上
chartester.Curr_Char='a'; 運行Curr_Char的Set方法, 觸發事件
Console.WriteLine(事件處理結果:{0},chartester.Curr_Char);
chartester.Curr_Char='b';
Console.WriteLine(事件處理結果:{0},chartester.Curr_Char);
chartester.Curr_Char='x';
Console.WriteLine({0},chartester.Curr_Char);
Console.WriteLine();
}
static void Change_X(Object source, CharEventArgs e)
{
if(e.CurrChar=='x' e.CurrChar='X')
{
Console.Write(觸發的字元是x,);
Console.Write(把x替為:);
e.CurrChar='';
}
else
Console.Write(觸發的字元不是x,);
}
}
運行結果:
觸發的字元不是x,事件處理的結果a
觸發的字元不是x,事件處理的結果b
觸發的字元是x,把x替為:?