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