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








评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老陈聊架构

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值