1 private void button1_Click(object sender, EventArgs e)
2 {
3 Form2 f = new Form2();
4 //第一点:简洁
5 //action and lambda
6 f.alEmethod += (s => this.textBox1.Text = s);
7 //delegate and method
8 f.dmEmethod += delegate(String s){this.textBox1.Text = s;};
9 f.ShowDialog();
10 }
在第一个窗口添加一个按钮并添加点击监听
1 public partial class Form2 : Form
2 {
3 //第二点:复杂,冗余
4 //使用Action和Lamdba
5 public event Action<String> alEmethod;
6
7 //使用自定义delegate和method
8 public delegate void ChangeTextDelegate(String s);
9 public event ChangeTextDelegate dmEmethod;
10
11 public Form2()
12 {
13 InitializeComponent();
14 }
15 // action 按钮
16 private void button1_Click(object sender, EventArgs e)
17 {
18 if(alEmethod!=null){
19 alEmethod(this.textBox1.Text);
20 }
21 }
22 // delegate 按钮
23 private void button2_Click(object sender, EventArgs e)
24 {
25 if(dmEmethod!=null){
26 alEmethod(this.textBox1.Text);
27 }
28 }
29 }
很明显了,使用lambda+系统委托更优美
时间: 2024-10-09 20:52:54