创建一个继承自基础 class 并包含实例变量的构造函数

Creating a constructor that inherits from a base class and includes an instance variable

我正在尝试在派生的 class 中创建一个构造函数,它从基础 class 中获取 initialBalance 和一个实例变量调用 interestRate。我收到错误代码 CS7036,没有给定的参数对应于 'Account.Account(decimal)' 的必需形式参数 'balance'。

namespace BankApp
{
    class SavingsAccount : Account
    {
        private decimal interestRate;
        private decimal interest;

        public SavingsAccount(decimal percentage, decimal balance) // error is thrown here
        {
            interestRate = percentage;
            IntialBalance = balance;
        }  

        public void CalculateInterest()
        {
           interest = IntialBalance * interestRate;
        }
    }
}
namespace BankApp
{
    class Account
    {
        private decimal accountBalance;

        //constructor 
        public Account(decimal balance)
        {
            IntialBalance = balance; // validate the initial balance in property
        }
        // ensures intial balance is >= 0
        public decimal IntialBalance
        {
            get { return accountBalance; }
            set
            {
                if (value >= 0)
                    accountBalance = value;
                else
                    throw new ArgumentOutOfRangeException("IntialBalance", value, "Intial balance must be >= 0");
            }
        }
        // Returns current balance
        public decimal Balance
        {
            get { return accountBalance; }
        }
        // deposits into account
        public decimal Credit()
        {
            Console.WriteLine("Enter the amount you would like to deposit: ");
            decimal deposit = Convert.ToInt32(Console.ReadLine());

            accountBalance += deposit;
            return accountBalance;
        }
        // withdrawl from account
        public decimal Debit()
        {
            Console.WriteLine("Enter the amount you would like to withdrawl: ");
            decimal withdrawl = Convert.ToInt32(Console.ReadLine());

            if (accountBalance >= withdrawl)
                accountBalance = accountBalance - withdrawl;
            else
                Console.WriteLine("Debit amount exceeded account balance");
            return accountBalance;
        }
    }
}

没关系,这就是我想出的。我一直在尝试添加 : base(decimal balance) 而不仅仅是 : base (balance)。如果有更好的方法来做到这一点,我很想看看。我对编程很陌生。谢谢

 public SavingsAccount(decimal balance, decimal percentage) : base( balance) 
        {
            interestRate = percentage;
            InitialBalance = balance;
        }

发生此错误是因为您的 Account class 没有默认构造函数。当您创建 SavingsAccount 的实例时,它首先尝试创建 Account 的实例,但不知道为您提供的唯一构造函数的“balance”参数提供什么。

您可以将默认构造函数添加到 Account class 以使错误消失,但您必须手动设置平衡。

最简单的解决方案是像这样调用接收余额的基本构造函数:

public SavingsAccount(decimal percentage, decimal balance) : base(balance)
{
    interestRate = percentage;            
}

注意第一行末尾的 : base(balance)

另请注意,我们不再需要这一行 IntialBalance = balance;,因为基础构造函数将在调用时分配该值。