C#高级语法_委托
主从窗体之间的通信
主窗体:
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 WindowsFormsApp1
{public partial class FrmMain : Form{public FrmMain(){InitializeComponent();}//2.根据委托定义方法private void ReceiveMsg(string msg, string consoleName){this.label1.Text += $"来自{consoleName}的消息:{msg}\r\n";}/// <summary>/// 创建子窗体/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button1_Click(object sender, EventArgs e){for (int i = 1; i < 4; i++){ Form1 form = new Form1($"子窗体{i}");//4.委托变量和方法关联form.delegateReceiveMsg += ReceiveMsg;form.Show();}}/// <summary>/// 关闭子窗体/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button3_Click(object sender, EventArgs e){// 遍历所有打开的窗体// 使用ToList()创建副本,避免在遍历中修改集合引发异常foreach (var form in Application.OpenForms.OfType<Form1>().ToList()){// 关闭子窗体form.Close();}}}//1.定义委托public delegate void DelegateMsgBtoA(string msg, string consoleName);
}
子窗体:
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 WindowsFormsApp1
{public partial class Form1 : Form{//3.创建委托变量public DelegateMsgBtoA delegateReceiveMsg = delegate { };public Form1(){InitializeComponent();}public Form1(string name){InitializeComponent(); this.Text = name;}private void button1_Click(object sender, EventArgs e){//5.通过委托变量调用方法delegateReceiveMsg.Invoke(this.textBox1.Text, this.Text);}}
}