步步为营-26-多播委托
事件本质:多播委托;多播委托本质:一个委托指向多个函数
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Delegate_DuoBo { //1 声明一个委托无参数,无返回值 public delegate void DuoBoDelegate (); class Program { static void Main(string[] args) { DuoBoDelegate del = new DuoBoDelegate(Test1); del += Test3; del += Test4; del += Test2; del -= Test4; del(); Console.Read(); } //根据委托定义方法 public static void Test1() { Console.WriteLine("Test1"); } public static void Test2() { Console.WriteLine("Test2"); } public static void Test3() { Console.WriteLine("Test3"); } public static void Test4() { Console.WriteLine("Test4"); } } }
窗体间通过委托传值
创建两个Form
form1需要将ShowText方法传递给Form2,所以需要
1在Form2中定义委托用于接受Form1中的ShowText方法
2同时修改构造函数,
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Delegate_Window { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnShowWinfrom2_Click(object sender, EventArgs e) { //把方法传给form2 Form form2 = new Form2(ShowText); form2.Show(); } public void ShowText(string str) { lbl.Text = str; } } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Delegate_Window { public delegate void del(string str); public partial class Form2 : Form { //存储Form1传过来的委托 private del _del; public Form2(del dlegt) { InitializeComponent(); this._del = dlegt; } private void button1_Click(object sender, EventArgs e) { this._del(textBox1.Text.Trim()); } private void Form2_Load(object sender, EventArgs e) { } } }