单播委托

有难点,两个窗口如何传值呢???

用到了委托的概念,类似于传一个方法。

也很简单。具体看代码。

需求:窗口1 有一个按钮 点一下,弹出窗口2。窗口2有一个输入框和按钮,点一下按钮将输入框的值显示到窗口1的label上。
image.png

窗口1的代码

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. namespace WindowsFormsApp1
  11. {
  12. public partial class Form1 : Form
  13. {
  14. public Form1()
  15. {
  16. InitializeComponent();
  17. }
  18. // new 窗口2的时候 把方法传进去
  19. private void button1_Click(object sender, EventArgs e)
  20. {
  21. Form2 Form2 = new Form2(ShowMsg);
  22. Form2.ShowDialog();
  23. }
  24. //改变 窗口的具体方法。
  25. private void ShowMsg(string str)
  26. {
  27. label1.Text = str;
  28. }
  29. }
  30. }

窗口2的代码

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. namespace WindowsFormsApp1
  11. {
  12. //1.声明一个委托
  13. public delegate void CeShi(string str);
  14. public partial class Form2 : Form
  15. {
  16. // 2.声明一个委托变量
  17. public CeShi _ceShi;
  18. public Form2(CeShi ceShi)
  19. {
  20. // 3.将传来的方法指向委托类。
  21. _ceShi = ceShi;
  22. InitializeComponent();
  23. }
  24. private void button1_Click(object sender, EventArgs e)
  25. {
  26. //4. 执行方法
  27. _ceShi(textBox1.Text);
  28. }
  29. }
  30. }

多播委托

一个委托对象可以指定多个函数

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace _15多播委托
  7. {
  8. public delegate void DelTest();
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13. DelTest del = T1;
  14. del += T2;
  15. del += T3;
  16. del+= T4;
  17. del -= T3;
  18. del -= T1;
  19. del();
  20. Console.ReadKey();
  21. }
  22. public static void T1()
  23. {
  24. Console.WriteLine("我是T1");
  25. }
  26. public static void T2()
  27. {
  28. Console.WriteLine("我是T2");
  29. }
  30. public static void T3()
  31. {
  32. Console.WriteLine("我是T3");
  33. }
  34. public static void T4()
  35. {
  36. Console.WriteLine("我是T4");
  37. }
  38. }
  39. }