一、委托(delegate)
委托是一种数据类型
委托是存放符合某种方法签名的方法的地址的集合
解决方法无法作为参数传递
例:有两个方法,分别是中文打招呼和英文打招呼,两个方法作为参数来传递
class Program
{
static void Main(string[] args)
{
Greet("李大锤",English);//调用打招呼方法,并把用什么语言打招呼的方法当作参数调用
Console.ReadLine();
}
//定义一个委托
public delegate void GreetDelegate(string name);
//打招呼方法
public static void Greet(string name,GreetDelegate _GDL)//_GDL就是当前的委托对象
{
_GDL(name);
}
//中文打招呼
public static void Chinese(string name)
{
Console.WriteLine("早上好"+name);
}
//英文打招呼
public static void English(string name)
{
Console.WriteLine("GoodMorning" + name);
}
}
运行结果:
二、简单的窗体传值
例:
Form1:
Form2:
Form1代码:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string txt = text1.Text;
Form2 f2 = new Form2(txt,Show);//利用委托给调用Show()方法给文本框赋值
text1.Text = "";
f2.Show();
}
//将字符串赋值给文本框
public void Show(string str)
{
text1.Text = str;
}
}
Form2代码:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private MyDelegate _mdl;//定义一个委托变量来接受传过来的委托
public Form2(string str,MyDelegate mdl): this()
{
text2.Text = str;
this._mdl = mdl;//给委托赋值
}
private void button1_Click(object sender, EventArgs e)
{
string txt2 = text2.Text;
this._mdl(txt2);//利用委托给f1的文本框赋值
this.Close();
}
//定义一个委托
public delegate void MyDelegate(string str);
}