【问题标题】:Accessing class's properties after using List<>使用 List<> 后访问类的属性
【发布时间】:2017-04-15 13:59:21
【问题描述】:

我是 C# 的初学者,我有一个与基于使用类的继承和多态性相关的特定问题。我正在工作的任务是一个银行帐户,我必须使用三个类——一个是基类,而另外两个是派生类。

基类称为“BankAccount”,两个派生类是“CheckingAccount”和“SavingsAccount”。此外,我已经声明了“CheckingAccount”和“SavingAccount”的对象,并且它们存储在 List 类中。之后,我尝试使用组合框的“SelectedIndexChange”事件根据派生类的属性相应地填充我的作业的 GUI 标签。

问题是程序不检查列表类的存储元素是否被识别为特定类型。下面包含我的程序和类的代码。

 private void comboBoxAccountNumber_SelectedIndexChanged(object sender,  EventArgs e)
    {

        if (selectedBankAccount[0] is CheckingAccount)
        {
            labelOwnerID.Text = selectedBankAccount[0].AccountNumber;
            labelBalance.Text = selectedBankAccount[0].Balance.ToString("c");

        }

        else if (selectedBankAccount[1] is CheckingAccount)
        {
            labelOwnerID.Text = selectedBankAccount[1].AccountNumber;
            labelBalance.Text = selectedBankAccount[1].Balance.ToString("c");

        }


    }

     List<BankAccount> selectedBankAccount = new List<BankAccount> ();

    SavingsAccount savs1_Account;
    CheckingAccount chek1_Account;
    SavingsAccount savs2_Account;
    CheckingAccount chek2_Account;


    private void FormBankOfYourSelf_Load(object sender, EventArgs e)
    {
        savs1_Account = new SavingsAccount("0001", "31-1000", 100m, 0.01);
        chek1_Account = new CheckingAccount("0001", "44-1000", 250m, true);
        savs2_Account = new SavingsAccount("0002", "31-1001", 1000m, 0.0125);
        chek2_Account = new CheckingAccount("0002", "44-1001", 500m, false);  
        selectedBankAccount.Add(chek1_Account);
        selectedBankAccount.Add(chek2_Account);

        comboBoxAccountNumber.Items.Add(selectedBankAccount[0].AccountNumber);
        comboBoxAccountNumber.Items.Add(selectedBankAccount[1].AccountNumber);


    }



 public abstract class BankAccount
{
    // Fields - The data we want to store
    // Naming convention for fields is to use underscore before the name
    protected string  _customerId;
    protected string  _accountNumber;
    protected decimal _balance;

    //Properties - Allow access to fields (Get/Set)
    // Get = read access
    // Set = write (modify) access
    public string CustomerId
    {
        get { return _customerId; }
        set { _customerId = value; }
    }

    public string AccountNumber
    {
        get { return _accountNumber; }
        set { _accountNumber = value; }
    }

    public decimal Balance
    {
        get { return _balance; }
    }

    // Methods - The action or behaviors the class can do
    // almost always, define the constructor and ToString methods
    // Constructor creates (instantiates a new object)
    public BankAccount(string customerId, string accountNumber, decimal initialBalance)
    {
        //fields are set = to the parameters(inputs from the form)
        _customerId = customerId;
        _accountNumber = accountNumber;
        _balance = initialBalance;
   }

    public abstract bool Deposit(decimal depositAmount);
    //{
    //    // If the depositAmount is less then 0 then RETURN false
    //    if (depositAmount <= 0)
    //    {
    //        return false;
    //    }

    //    // Otherwise, complete the deposit and RETURN true
    //    _balance += depositAmount;
    //    return true;
    //}

    public abstract bool Withdraw(decimal withdrawAmount);
    //{
    //    // If the withdrawAmount is greater than the balance or less then or equal to 0 
    //    // then RETURN false (don't allow withdrawal)
    //    if (withdrawAmount > _balance || withdrawAmount <= 0)
    //    {
    //        return false;
    //    }

    //    // Otherwise, complete the withdrawal and return true
    //    _balance -= withdrawAmount;
    //    return true;
    //}


   public class CheckingAccount : BankAccount
   {
    //private string _customerID;
    //private string _accountNum;
    //private decimal _initBalance;
    private bool _overdraftProtection;

    public CheckingAccount(string customerId, string accountNum, decimal initialBalance, bool overDraft)
        :base(customerId, accountNum, initialBalance)
    {
        //_customerID = customerId;
        //_accountNum = accountNum;
        //_initBalance = initialBalance;
        _overdraftProtection = overDraft;
    }

    public bool OverDraftProtection
    {
        get { return _overdraftProtection; }

        set { _overdraftProtection = value; }
    }

    public override bool Deposit(decimal depositAmount)
    {
        if(depositAmount > 0)
        {
            _balance += depositAmount;
            return true;
        }

        else
        {
            return false;
        }
    }

    public override bool Withdraw(decimal withdrawAmount)
    {
        if(withdrawAmount <= _balance || withdrawAmount > 0 )
        {
            _balance -= withdrawAmount;
            return true;
        }

        else
        {
            return false;
        }
    }




}

**更新:我注意到当我运行我的程序时,即使我在组合框中选择了不同的项目,它也不会相应地将值更改为选定的项目。下面是我运行的程序,选择了不同的项目。

First selected item in combobox
Second selected item in combobox

【问题讨论】:

  • 如果你只使用基类的属性(AccountNumberBalance),你为什么要关心派生类是什么?

标签: c# list class object inheritance


【解决方案1】:

从发布的 cmets 发现问题在于代码没有选择 ComboBox 中选择的 BankAccount。不知道 ComboBox 是如何填充的。最简单的方法是使用 selected 索引,假设 comboBoxAccountNumber 填充了 selectedBankAccount 集合。

private void comboBoxAccountNumber_SelectedIndexChanged(object sender,  EventArgs e)
{
    BackAccount account = selectedBankAccount[comboBoxAccountNumber.SelectedIndex]

    labelOwnerID.Text = account.AccountNumber;
    labelBalance.Text = account.Balance.ToString("c");
}

【讨论】:

  • 是的,这确实有道理。几个小时前,我发现了程序不读取代码的问题,这表明它不知道组合框中的项目。非常感谢你的帮助。在考虑您的方法时,我采用了不同的方法。
【解决方案2】:

您的列表是BankAccount 类型,因此您需要将对象转换为要使用的特定继承类,然后属性才可用

使用is 关键字,然后使用as 关键字在性能方面代价高昂,因为您基本上要进行两次强制转换。最好使用as 关键字并测试是否为空

CheckingAccount account = selectedBankAccount[0] as CheckingAccount
if(account != null)
{
    //account is of type CheckingAccount so the additional 
    //CheckingAccount properties should be available via the account variable
}

【讨论】:

  • 我明白了。嗯...我尝试了类似的方法将列表类的元素转换为预期的继承类,但是,它不起作用。我注意到,当我运行我的程序时,即使我在组合框中选择了不同的项目,它也不会相应地将值更改为选定的项目。
猜你喜欢
  • 2016-12-06
  • 1970-01-01
  • 2020-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-22
  • 1970-01-01
  • 2012-06-03
相关资源
最近更新 更多