[英]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 enterbase.CalculateInterest
method all it gives me forInterestRate
is0
.当我输入
base.CalculateInterest
方法时,当我调用loanAccount.CalculateInterest(4)
时,它为InterestRate
提供的所有信息都是0
。 Why?为什么? doesn't it have to be 2.35 since this property has a default value?
因为此属性具有默认值,所以不必一定是2.35吗?
我设法回答了我的问题,问题是BankAccount
中的属性是virtual
,然后在LoanAccount
被覆盖,因此,当我调用CalculateInterest
它使用派生类( LoanAccount
)中的重写属性而不是虚拟的(在BankAccount
),这导致我认为使用虚拟属性应该非常小心。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.