1. 程式人生 > >C#委託事件應用例項

C#委託事件應用例項

委託

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();
}