private void button1_Click(object sender, System.EventArgs e)
{
myButton btn = new myButton();
btn.TxtChange +=new myEventHandler(button_TxtChange);
string[] values = {"AAA","BBB","CCC","DDD","EEE"};
for( int i = 0; i < 5; i++ )
{
//主要是让程序有个阻塞输出,可以停留一会儿,让你一次看个够J,对理解委托没什么意义。
System.Threading.Thread.Sleep(2000);
//进行赋值,从而引发事件而直接调用button_TxtChange事件处理函数。
btn.Test(values[i]);
}
}
private void button_TxtChange(object sender, System.EventArgs e)
{
Console.WriteLine( " Button实例新值。其值为:" + ((myButton)sender).Text );
}
// 定义委托处理程序
public delegate void myEventHandler(object sender,System.EventArgs e);
public class myButton
{
public event myEventHandler TxtChange; //定义一个事件委托的引用,以备外部进行事件的绑定.
public string Text;
public void Test(string text)
{
this.Text = text;
System.EventArgs e = new EventArgs(); //这里是事件的基类实例.
ChangeTxt(e); //调用事件处理函数.
}
private void ChangeTxt(System.EventArgs e)
{
if( TxtChange != null )
TxtChange(this,e);//真正调用外部指派的处理函数.
}
}