我遇到了一个小问题,我不明白为什么,很容易绕过它,但我仍然想了解。
我有以下类(class):
public class AccountStatement : IAccountStatement
{
public IList<IAccountStatementCharge> StatementCharges { get; set; }
public AccountStatement()
{
new AccountStatement(new Period(new NullDate().DateTime,newNullDate().DateTime), 0);
}
public AccountStatement(IPeriod period, int accountID)
{
StatementCharges = new List<IAccountStatementCharge>();
StartDate = new Date(period.PeriodStartDate);
EndDate = new Date(period.PeriodEndDate);
AccountID = accountID;
}
public void AddStatementCharge(IAccountStatementCharge charge)
{
StatementCharges.Add(charge);
}
(注意开始日期、结束日期、accountID 是...的自动属性)
如果我这样使用它:
var accountStatement = new AccountStatement{
StartDate = new Date(2007, 1, 1),
EndDate = new Date(2007, 1, 31),
StartingBalance = 125.05m
};
当我尝试使用“AddStatementCharge”方法时:我最终得到一个“空”StatementCharges 列表......在逐步的过程中,我清楚地看到我的列表获得了一个值,但是一旦我退出实例化行,我的列表变为“空”
最佳答案
这段代码:
public AccountStatement()
{
new AccountStatement(new Period(new NullDate().DateTime,newNullDate().DateTime), 0);
}
无疑不是您想要的。这生成了 AccountStatement 的第二个实例,但不对其执行任何操作。
我想你的意思是这样的:
public AccountStatement() : this(new Period(new NullDate().DateTime, new NullDate().DateTime), 0)
{
}
关于C# 3.0 - 对象初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/127817/