简体   繁体   中英

Default value of virtual property

So I have abstract class with following absract class:

public abstract class BankAccount
{
    public virtual double InterestRate { get; protected set; } = 2.35;

    public virtual double CalculateInterest(int months)
    {
        return months * this.InterestRate;
    }
}

then I have derived class:

public class LoanAccount : BankAccount
{
    public override double CalculateInterest(int months)
    {
        if ((this.Customer is Individual && months <= 3) || (this.Customer is Company && months <= 2))
        {
            this.InterestRate = 1.00;
        }
        return base.CalculateInterest(months);
    }
}

here is the invocation:

static void Main(string[] args)
{
    List<BankAccount> bankAccounts = new List<BankAccount>(10)
    {
        new LoanAccount(new Individual(), 1000)
    };

    Console.WriteLine(bankAccounts[0].CalculateInterest(4));
}

When I call loanAccount.CalculateInterest(4) when I enter base.CalculateInterest method all it gives me for InterestRate is 0 . Why? doesn't it have to be 2.35 since this property has a default value?

我设法回答了我的问题,问题是BankAccount中的属性是virtual ,然后在LoanAccount被覆盖,因此,当我调用CalculateInterest它使用派生类( LoanAccount )中的重写属性而不是虚拟的(在BankAccount ),这导致我认为使用虚拟属性应该非常小心。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM