将 C# 委托与事件一起使用

在这里插入图片描述
.NET 委托是可以在运行时引用内存中的静态方法和实例方法的对象,并且可以在您的程序中调用这些方法。在本教程中,我将向您展示如何在 C# 中创建和使用委托。

为了解释委托及其在现实世界程序中的使用,我正在创建一个 BankAccount 类,我将在其中使用 C# 委托关键字声明一个委托。

public class BankAccount
{
    int amount = 0; 
    // Declare Delegate Type Object
    public delegate void BankDelegate(int oldBalance, int newBalance); 
    // Create Delegate Type Events 
    public event BankDelegate OnDeposit;
    public event BankDelegate OnWithdraw; 
    public void Deposit(int a)
    {
        // Fire OnDeposit Event and pass old and new balance amount
        OnDeposit(this.amount, this.amount + a);         
 
        this.amount += a;         
 
    } 
    public void Withdraw(int a)
    {
        // Fire OnWithdraw Event and pass old and new balance amount
        OnWithdraw(this.amount, this.amount - a);
         
        this.amount -= a;
    }
} 

要测试 BankAccount 类,请使用 C# 创建一个 Windows 窗体应用程序,并在 BankAccount 类的 Form Load 事件中创建对象,如下所示
在这里插入图片描述

// Declare BankAccount class variable 
BankAccount account = null;
  
private void Form1_Load(object sender, EventArgs e)
{
    account = new BankAccount();
      
   // Attach Event Handlers with Events
   account.OnDeposit += new BankAccount.BankDelegate(account_OnDeposit);
   account.OnWithdraw += new BankAccount.BankDelegate(account_OnWithdraw);
} 

以下代码在存款和取款按钮单击事件上调用 BankAccount 类方法。

private void btnDeposit_Click(object sender, EventArgs e)
{
    account.Deposit(Int32.Parse(textBox1.Text)); 
}
 
private void btnWithdraw_Click(object sender, EventArgs e)
{
    account.Withdraw(Int32.Parse(textBox1.Text)); 
}

以下方法是附加有委托类型事件 OnDeposit 和 OnWithdraw 的事件处理程序方法

void account_OnDeposit(int oldBalance, int newBalance)
{
    label4.Text = oldBalance.ToString();
    label5.Text = newBalance.ToString(); 
}
 
void account_OnWithdraw(int oldBalance, int newBalance)
{
    label4.Text = oldBalance.ToString();
    label5.Text = newBalance.ToString(); 
} 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Cool2Feel

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

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

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

打赏作者

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

抵扣说明:

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

余额充值