委托
1.委托是什么?
个人理解是:
①委托是一种特殊的类
②委托可以绑定多个方法(含有相同的传入参数)
2.委托的应用
①初级应用
先定义委托事件:
public delegate void PerformCalculation(string text);
定义相关方法:
-
public void Print1(string p1)
-
{
-
MessageBox.Show(
"Print1" + p1);
-
}
-
public void Print2(string p2)
-
{
-
MessageBox.Show(
"Print2" + p2);
-
}
定义点击事件:
-
private void button1_Click(object sender, EventArgs e)
-
{
-
PerformCalculation Print = Print1;
-
Print(
"p1");
-
}
-
-
private void button2_Click(object sender, EventArgs e)
-
{
-
PerformCalculation Print = Print1;
-
Print(
"p1");
-
}
即可实现委托调用不同的方法。
效果图:
②实战应用-进度条的实现
定义委托方法:
public delegate void DelegateMethod(int position, int maxValue);
定义相关类:
-
public
class
TestDelegate
-
{
-
public DelegateMethod OnDelegate;
-
public void DoDelegateMethod()
-
{
-
int maxValue =
100;
-
for (
int i =
0; i < maxValue; i++)
-
{
-
if (
this.OnDelegate !=
null)
-
{
-
this.OnDelegate(i, maxValue);
-
}
-
}
-
}
-
-
}
定义点击事件:
-
private void barButtonItem1_ItemClick(object sender, ItemClickEventArgs e)
-
{
-
TestDelegate test =
new TestDelegate();
-
this.textBox1.Text =
"";
-
this.progressBar1.Value =
0;
-
test.OnDelegate =
new DelegateMethod(
delegate (
int i,
int maxValue)
-
{
-
this.textBox1.Text += i.ToString() + Environment.NewLine;
-
this.progressBar1.Maximum = maxValue;
-
this.progressBar1.Value++;
-
});
-
test.DoDelegateMethod();
-
}