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("代理陈晓玲", "代理");
}
}
}