簡體   English   中英

虛擬屬性的默認值

[英]Default value of virtual property

所以我有下面的抽象類的抽象類:

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

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

然后我派生類:

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

這是調用:

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

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

當我輸入base.CalculateInterest方法時,當我調用loanAccount.CalculateInterest(4)時,它為InterestRate提供的所有信息都是0 為什么? 因為此屬性具有默認值,所以不必一定是2.35嗎?

我設法回答了我的問題,問題是BankAccount中的屬性是virtual ,然后在LoanAccount被覆蓋,因此,當我調用CalculateInterest它使用派生類( LoanAccount )中的重寫屬性而不是虛擬的(在BankAccount ),這導致我認為使用虛擬屬性應該非常小心。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM