委托的应用是非常广泛的,在winform桌面开发中,算是家常便饭
委托,通俗一点来讲,就是:我要做一件事情,我没有权限去做,然后我把它交给另一个有权限的人去;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DelegateDemo
{
public partial class Form1 : Form
{
private Form2 frm2;
public Form1()
{
InitializeComponent();
this.button1.Click += (sender, e) =>
{
if (frm2 == null)
{
frm2 = new Form2();
frm2.operate = Operate;
}
frm2.Show();
};
}
private void Operate(int number, string type)
{
if (type.Equals("+"))
{
int num = Convert.ToInt32(this.label1.Text);
this.label1.Text = Convert.ToString(num + number);
}
else
{
int num = Convert.ToInt32(this.label1.Text);
this.label1.Text = Convert.ToString(num - number);
}
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DelegateDemo
{
public partial class Form2 : Form
{
public Action<int,string> operate;
public Form2()
{
InitializeComponent();
this.button1.Click += (sender, e) =>
{
//增加
if (operate != null && IsNumber())
operate(Convert.ToInt32(this.textBox1.Text),"+");
};
this.button2.Click += (sender, e) =>
{
//减少
if (operate != null && IsNumber())
operate(Convert.ToInt32(this.textBox1.Text),"");
};
}
private bool IsNumber()
{
bool bl = true;
int i;
if (!int.TryParse(this.textBox1.Text, out i))
{
MessageBox.Show("输入非法");
bl = false;
}
return bl;
}
}
}
要改变form1中的0,但是from1中没有值,我无法知道它是要加还是减,加多少还是减多少,这些信息只有在form2中才能知道,
在from1中写好方法,定义一个值,这个值是具体的运算用值,另一个值,则在调用的时候输入不同的实参就可以判断出来是增加还是减少了