c#中添加自定义事件的例子
using System;
using System.Collections.Generic;
using System.Text;
namespace test
{
/// <summary>
/// 声明一个自定义的委托
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public delegate void CharEeventHandler(object sender,CharEventArgs e);
public class CharEventArgs:EventArgs
{
public char CurrChar;
public CharEventArgs(char CurrChar)
{
this.CurrChar = CurrChar;
}
}
public class CharChecker
{
char curr_char;
public event CharEeventHandler CharTest;
public char Curr_char
{
get { return curr_char; }
set
{
if (CharTest != null)
{
CharEventArgs myenen = new CharEventArgs(value);
curr_char = myenen.CurrChar;
this.CharTest(this, myenen);
}
}
}
}
class Program
{
static void Main(string[] args)
{
CharChecker chartester = new CharChecker();
chartester.CharTest += new CharEeventHandler(Change_X);
chartester.Curr_char = 'a';
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();
Console.ReadLine();
}
static void Change_X(object source, CharEventArgs e)
{
if (e.CurrChar == 'x')
{
Console.Write("触发的字符是x,");
Console.Write("把x替换成: ");
e.CurrChar = '?';
}
else
{
Console.Write("触发的字符不是x,");
}
}
}
}
using System.Collections.Generic;
using System.Text;
namespace test
{
/// <summary>
/// 声明一个自定义的委托
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public delegate void CharEeventHandler(object sender,CharEventArgs e);
public class CharEventArgs:EventArgs
{
public char CurrChar;
public CharEventArgs(char CurrChar)
{
this.CurrChar = CurrChar;
}
}
public class CharChecker
{
char curr_char;
public event CharEeventHandler CharTest;
public char Curr_char
{
get { return curr_char; }
set
{
if (CharTest != null)
{
CharEventArgs myenen = new CharEventArgs(value);
curr_char = myenen.CurrChar;
this.CharTest(this, myenen);
}
}
}
}
class Program
{
static void Main(string[] args)
{
CharChecker chartester = new CharChecker();
chartester.CharTest += new CharEeventHandler(Change_X);
chartester.Curr_char = 'a';
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();
Console.ReadLine();
}
static void Change_X(object source, CharEventArgs e)
{
if (e.CurrChar == 'x')
{
Console.Write("触发的字符是x,");
Console.Write("把x替换成: ");
e.CurrChar = '?';
}
else
{
Console.Write("触发的字符不是x,");
}
}
}
}
运行结果为:
posted on 2008-07-14 17:20 Junda.chen 阅读(1084) 评论(2) 编辑 收藏 举报