当前位置: 首页 > news >正文

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);}}
}
http://www.dtcms.com/a/336667.html

相关文章:

  • 力扣第463场周赛
  • 17-线程
  • uC/OS - III 系统DEBUG时内核对象统计信息
  • 模拟实现 useEffect 功能
  • 配置 NVIDIA RTX 5090 + sm_120 + flashattention,已跑通一个大模型 ~~
  • clion 如何调试 redis(在 mac 上)
  • AMBA-AXI and ACE协议详解(三)
  • 期望分位数回归模型
  • 利用pypy加速pyxlsbwriter生成xlsb文件
  • 五、redis入门 之 客户端连接redis
  • 日语学习-日语知识点小记-进阶-JLPT-N1阶段蓝宝书,共120语法(3):21-30语法
  • 雷卯针对香橙派Orange Pi Kunpeng Pro开发板防雷防静电方案
  • CloudBeaver:基于浏览器的DBeaver
  • 机器学习案例——对好评和差评进行预测
  • 当AI替我“搬砖”,我的价值是什么?
  • 21.AlexNet
  • 金山办公的服务端开发工程师-25届春招部分笔试题
  • C# Newtonsoft.Json 反序列化子类数据丢失问题
  • DBeaver连接MySQL 8报错连接丢失
  • HTTP协议-3-HTTP/2是如何维持长连接的?
  • JAVA后端开发——Token自动续期机制的必要性
  • 【Linux内核】Linux信号机制
  • 【Linux】五种IO模型
  • JVM学习笔记-----StringTable
  • react 错误边界
  • Python 内置模块 collections 常用工具
  • 【撸靶笔记】第二关:GET -Error based -Intiger based
  • Spring Framework :IoC 容器的原理与实践
  • CW32L011_电机驱动器开发板试用
  • 工作中使用到的时序指标异常检测算法 TRPS 【Temporal Residual Pattern Similarity】和 K-sigma 算法