c#中两个窗口传值用委托实现
(1)从数据结构来讲,委托和类一样是一种用户自定义类型
(2)从设计模式来讲,委托提供了方法的抽象
我在c#书上找到了委托的简介:委托类似于函数指针,他是一种引用类型,它引用的就是函数。
为了帮助理解,我在书上查了查委托的类型和赋值
-
1 . 委托类型与委托变量的声明。
修饰符 delegate 返回类型 委托名 (参数列表)
public delegate void DelTest(string str1,string strl2);2.声明一个委托类型的变量与声明一个普通变量方式一样。(委托其实就是一种类型–一种引用类型)
3.委托实例化 new 委托类型名(方法名)
4.委托简写和赋值(语法糖)
先把结果放上 (form2通过委托调用form1的方法)
form1的代码
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f = new Form2(ShowText);
f.Show();
// this.textBox1.Text = Class1.name;
// this.textBox1.Tex = Class1.age;
void ShowText(string str1, string str2)
{
this.textBox1.Text =str1;
this.textBox2.Text = str2;
}
}
}```
form2的代码
public partial class Form2 : Form
{
public delegate void DelTest(string str1,string strl2);//声明委托
private DelTest _del;// 定义委托变量
public Form2(DelTest del)
{
this._del = del;//委托变量指向form1的ShowText的函数
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this._del(textBox1.Text.Trim(), textBox2.Text.Trim());
}
}