步骤
1.声明委托
2.创建委托对象
3.创建委托方法
4.绑定委托
5.调用委托
界面
主窗体代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
// 1.声明委托(在命名空间)
public delegate void A_delegate(string value);
public delegate void B_delegate(string value1, string value2, string value3);
public delegate string C_delegate(string value);
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
// 4.绑定委托
frm2.setvalue_A1 += this.Setvalue1;
frm2.setvalue_A2 += this.Setvalue2;
frm2.setvalue_B += this.Setvalue3;
frm2.setvalue_C += this.Getvalue;
frm2.Show();
}
// 3.创建委托方法
public void Setvalue1(string value)
{
textBox1.Text = value;
}
public void Setvalue2(string value)
{
textBox2.Text = value;
}
public void Setvalue3(string value1, string value2, string value3)
{
textBox3.Text = value1 + value2 + value3;
}
public string Getvalue(string value)
{
return "C:" + value;
}
}
}
子窗体代码
using System;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
// 2.创建委托对象
public A_delegate setvalue_A1;
public A_delegate setvalue_A2;
public B_delegate setvalue_B;
public C_delegate setvalue_C;
private void button1_Click(object sender, EventArgs e)
{
// 5.调用委托
setvalue_A1?.Invoke(textBox1?.Text);
setvalue_A2?.Invoke(textBox2?.Text);
setvalue_B?.Invoke(textBox1?.Text, textBox2?.Text, textBox3?.Text);
textBox4.Text = setvalue_C?.Invoke(textBox1.Text);
}
}
}