namespace DelegateTest
{
public partial class Form1 : Form
{
public delegate void ShowTextValue(string text);//代理
public event ShowTextValue showText;//代理事件
public Form1()
{
InitializeComponent();
//把事件加入事件隊列中
showText += new ShowTextValue(SetText);
}
//開始代理
public void StartDelegate(string str) {
showText(str);
}
//設定文字框的值
private void SetText(string str) {
textBox1.Text = str;
}
//textBox1的TextChange事件
private void textBox1_TextChanged(object sender, EventArgs e)
{
showText(textBox1.Text);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//在關閉視窗時 去掉代理事件,因為沒載入一次表單就代理了SetText方法,
//如果不去掉,這個視窗開幾次 ,SetText方法就會執行幾次
//事件隊列中的方法會按順序執行
showText -= new ShowTextValue(SetText);
}
}
}
namespace DelegateTest
{
public partial class Form2 : Form
{
Form1 form1;
public Form2()
{
InitializeComponent();
}
private void SetText(string text)
{
textBox1.Text = text;
}
private void button1_Click(object sender, EventArgs e)
{
form1 = new Form1();
form1.showText += new Form1.ShowTextValue(SetText);
form1.Show();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
form1.StartDelegate(textBox1.Text);
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
form1.showText -= new Form1.ShowTextValue(SetText);
}
}
}
namespace DelegateTest
{
public class Control
{
public delegate void SomeHandler(object sender, EventArgs e);
public event SomeHandler someevent;
public Control() {
this.someevent += new SomeHandler(PrintStr);
this.someevent += new SomeHandler(PrintInt);
}
public void ReadStr() {
EventArgs e = new EventArgs();
someevent(this,e);
}
private void PrintStr(object sender, EventArgs e)
{
MessageBox.Show("我就是陳太漢!,陳曉玲就是我老婆","代理");
}
private void PrintInt(object sender, EventArgs e)
{
MessageBox.Show("你好,我就是陳太漢!,陳太漢就是我,哈哈哈哈哈", "代理");
}
}
}
namespace DelegateTest
{
public class Container
{
Control control = new Control();
public Container() {
control.someevent += new Control.SomeHandler(DelegateC);
control.ReadStr();
}
private void DelegateC(object sender, EventArgs e)
{
MessageBox.Show("代理陳曉玲", "代理");
}
}
}