我的目标是在尝试将余额降至零以下时抛出 NegativeBalanceException。就像这是一个真实的银行账户一样。我有 if 和 else 语句,但是把它们砍掉了,并试图学习 try、catch 和 throw 语句(最后也在阅读,但我认为这不适用于这里)。无论如何,如果我不输入任何内容就点击存款按钮,我就会设置一个 catch 语句的工作位置。但是,我不明白它希望我在哪里实现它以使其低于零。它在我的存款方式中吗?还是在实际的 btn_deposit 中?另外,使用 try catch 语句而不是 if else 语句的目的是什么?我是编程新手,我只是想学习。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public class BankAccount
{
decimal amount = 300.00m;
// Declare Delegate Type Object
public delegate void BankDelegate(decimal oldBalance, decimal newBalance);
// Create Delegate Type Events
public event BankDelegate OnDeposit;
public event BankDelegate OnWithdraw;
public void Deposit(decimal a)
{
{
if (a > 0)
{
OnDeposit(this.amount, this.amount + a);
this.amount += a;
}
else
{
MessageBox.Show("No!");
}
}
}
public void Withdraw(decimal a)
{
// Fire OnWithdraw Event and pass old and new balance amount
OnWithdraw(this.amount, this.amount - a);
this.amount -= a;
}
}
// 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);
}
private void btnDeposit_Click(object sender, EventArgs e)
{
try
{
account.Deposit(Convert.ToDecimal(textBox1.Text));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnWIthdraw_Click(object sender, EventArgs e)
{
account.Withdraw(Convert.ToDecimal(textBox1.Text));
}
void account_OnDeposit(decimal oldBalance, decimal newBalance)
{
label4.Text = oldBalance.ToString();
label5.Text = newBalance.ToString();
}
void account_OnWithdraw(decimal oldBalance, decimal newBalance)
{
label4.Text = oldBalance.ToString();
label5.Text = newBalance.ToString();
}
}
}