C#委托事件应用实例

本文详细介绍了委托的概念及其在软件开发中的应用。首先解释了委托的基本原理,即作为一种特殊类型的类能够绑定多个具有相同输入参数的方法。随后通过实例展示了如何利用委托进行方法调用,并进一步深入到实际项目中进度条更新功能的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

委托

1.委托是什么?

个人理解是:

①委托是一种特殊的类

②委托可以绑定多个方法(含有相同的传入参数)

2.委托的应用

①初级应用

先定义委托事件:

public delegate void PerformCalculation(string text);
定义相关方法:

  1. public void Print1(string p1)
  2. {
  3.     MessageBox.Show("Print1" + p1);
  4. }
  5. public void Print2(string p2)
  6. {
  7.     MessageBox.Show("Print2" + p2);
  8. }
定义点击事件:

  1. private void button1_Click(object sender, EventArgs e)
  2. {
  3. PerformCalculation Print = Print1;
  4. Print("p1");
  5. }
  6. private void button2_Click(object sender, EventArgs e)
  7. {
  8. PerformCalculation Print = Print1;
  9. Print("p1");
  10. }
即可实现委托调用不同的方法。

效果图:




②实战应用-进度条的实现

定义委托方法:

public delegate void DelegateMethod(int position, int maxValue);
定义相关类:

  1. public class TestDelegate
  2. {
  3. public DelegateMethod OnDelegate;
  4. public void DoDelegateMethod()
  5. {
  6. int maxValue = 100;
  7. for (int i = 0; i < maxValue; i++)
  8. {
  9. if (this.OnDelegate != null)
  10. {
  11. this.OnDelegate(i, maxValue);
  12. }
  13. }
  14. }
  15. }
定义点击事件:

  1. private void barButtonItem1_ItemClick(object sender, ItemClickEventArgs e)
  2. {
  3. TestDelegate test = new TestDelegate();
  4. this.textBox1.Text = "";
  5. this.progressBar1.Value = 0;
  6. test.OnDelegate = new DelegateMethod(delegate (int i, int maxValue)
  7. {
  8. this.textBox1.Text += i.ToString() + Environment.NewLine;
  9. this.progressBar1.Maximum = maxValue;
  10. this.progressBar1.Value++;
  11. });
  12. test.DoDelegateMethod();
  13. }








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值