首页 > Windows开发 > 详细

C# 委托,在多窗体数据传递的使用

时间:2020-08-09 20:15:56      阅读:120      评论:0      收藏:0      [点我收藏+]
  1. </pre>     在委托中,单播委托就是只能调用一个方法;委托中还有另一种方法,改方法能够实现调用多个方法,称为多播委托,
    方式就是“+=”,实现调用多个方法,也可以用“-=”将固定方法去掉。下面接着上个文章,我们来实现多窗体的通信。
    <p></p><p>主窗体</p>
    <pre name="code" class="csharp">namespace MoreContact
  2. {
  3. /// <summary>
  4. /// 委托定义
  5. /// </summary>
  6. public delegate void MoreContactDelegate(string word);
  7. public partial class FrmMain : Form
  8. {
  9. //声明委托
  10. MoreContactDelegate Message;
  11. public FrmMain()
  12. {
  13. InitializeComponent();
  14. //窗体实例化
  15. FrmOther1 f1 = new FrmOther1();
  16. FrmOther2 f2 = new FrmOther2();
  17. FrmOther3 f3 = new FrmOther3();
  18. f1.Show();
  19. f2.Show();
  20. f3.Show();
  21.  
  22. //调用委托变量与方法联系到一起
  23. Message = f1.Receive;
  24. Message += f2.Receive;
  25. Message += f3.Receive;
  26. }
  27. private string word;
  28. //通过单击调用委托实现固定的方法
  29. private void button1_Click(object sender, EventArgs e)
  30. {
  31. word = textBox1.Text;
  32. Message(word);
  33. }
  34.  
  35. private void button2_Click(object sender, EventArgs e)
  36. {
  37. word = "";
  38. Message(word);
  39. textBox1.Text = "";
  40. }
  41. }
  42. }
从窗体1-3程序都是一样:
  1. <pre name="code" class="csharp">namespace MoreContact
  2. {
  3. public partial class FrmOther1 : Form
  4. {
  5. public FrmOther1()
  6. {
  7. InitializeComponent();
  8. }
  9. //定义方法
  10. public void Receive(string word)
  11. {
  12. textBox1.Text = word;
  13. }
  14. }

C# 委托,在多窗体数据传递的使用

原文:https://www.cnblogs.com/ArthurJiang/p/13464529.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!