今天再次看了委托的教程,有了更深刻的认识。委托就好像js或者php里的闭包一样,把函数当作变量,然后可以调用一样。
写了个代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace weituo
{
//声明一个委托,委托必须要与被委托的方法保持一致
public delegate int deleMath(int x,int y);
public partial class Form5 : Form
{
public Form5()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
deleMath s; //委托是一个数据类型,所以我们像变量一样,先定义
mathOpt ma = new mathOpt(); //实例化对象
s = ma.Add; //赋值给委托,然后就可以调用了。
int k = s(2, 3);
MessageBox.Show(k.ToString());
}
}
public class mathOpt
{
public int Add(int x,int y)
{
return x+y;
}
public int subtract(int x,int y)
{
return x-y;
}
}
}
然后尝试父子窗口之间的传值
form1的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace weituo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void chuangzhi(string s)
{
textBox1.Text = s;
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2(chuangzhi);
frm2.txtfrm2.Text = textBox1.Text; //传到窗口2
frm2.ShowDialog();
}
}
}
form2的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace weituo
{
//与窗体1的ShowText方法签名相同的委托类型
public delegate void deleChuanzhi(string s);
public partial class Form2 : Form
{
public deleChuanzhi delecz1;
public Form2(deleChuanzhi delecz2)
{
this.delecz1 = delecz2;
InitializeComponent();
}
private void btnFrm2_Click(object sender, EventArgs e)
{
string ss = txtfrm2.Text;
this.delecz1(ss);
}
}
}