namespace DelegateTest
{
public partial class Form1 : Form
{
public delegate void ShowTextValue(string text);//代理
public event ShowTextValue showText;//代理事件
public Form1()
{
InitializeComponent();
//把事件加入事件队列中
showText += new ShowTextValue(SetText);
}
//开始代理
public void StartDelegate(string str) {
showText(str);
}
//设置文本框的值
private void SetText(string str) {
textBox1.Text = str;
}
//textBox1的TextChange事件
private void textBox1_TextChanged(object sender, EventArgs e)
{
showText(textBox1.Text);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//在关闭窗口时 去掉代理事件,因为没加载一次窗体就代理了SetText方法,
//如果不去掉,这个窗口开几次 ,SetText方法就会执行几次
//事件队列中的方法会按顺序执行
showText -= new ShowTextValue(SetText);
}
}
}
namespace DelegateTest
{
public partial class Form2 : Form
{
Form1 form1;
public Form2()
{
InitializeComponent();
}
private void SetText(string text)
{
textBox1.Text = text;
}
private void button1_Click(object sender, EventArgs e)
{
form1 = new Form1();
form1.showText += new Form1.ShowTextValue(SetText);
form1.Show();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
form1.StartDelegate(textBox1.Text);
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
form1.showText -= new Form1.ShowTextValue(SetText);
}
}
}
namespace DelegateTest
{
public class Control
{
public delegate void SomeHandler(object sender, EventArgs e);
public event SomeHandler someevent;
public Control() {
this.someevent += new SomeHandler(PrintStr);
this.someevent += new SomeHandler(PrintInt);
}
public void ReadStr() {
EventArgs e = new EventArgs();
someevent(this,e);
}
private void PrintStr(object sender, EventArgs e)
{
MessageBox.Show("我就是陈太汉!,陈晓玲就是我老婆","代理");
}
private void PrintInt(object sender, EventArgs e)
{
MessageBox.Show("你好,我就是陈太汉!,陈太汉就是我,哈哈哈哈哈", "代理");
}
}
}
namespace DelegateTest
{
public class Container
{
Control control = new Control();
public Container() {
control.someevent += new Control.SomeHandler(DelegateC);
control.ReadStr();
}
private void DelegateC(object sender, EventArgs e)
{
MessageBox.Show("代理陈晓玲", "代理");
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架