C#3.0 - 对象初始化程序

pml*_*que 2 c# .net-3.5

我有一点问题,我不明白为什么,这很容易解决,但我仍然想了解.

我有以下课程:

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);
    }
Run Code Online (Sandbox Code Playgroud)

}

(注意startdate,enddate,accountID是自动属性...)

如果我这样使用它:

var accountStatement = new AccountStatement{
                                              StartDate = new Date(2007, 1, 1),
                                              EndDate = new Date(2007, 1, 31),
                                              StartingBalance = 125.05m
                                           };
Run Code Online (Sandbox Code Playgroud)

当我尝试使用方法"AddStatementCharge:我最终得到一个"null"StatementCharges列表...在一步一步我清楚地看到我的列表得到一个值,但一旦我退出de instantiation行,我的列表变为"null"

Bra*_*son 18

这段代码:

public AccountStatement()
{
    new AccountStatement(new Period(new NullDate().DateTime,newNullDate().DateTime), 0);
}
Run Code Online (Sandbox Code Playgroud)

毫无疑问,这不是你想要的.这是AccountStatement的第二个实例,并且对它没有任何作用.

我认为你的意思是:

public AccountStatement() : this(new Period(new NullDate().DateTime, new NullDate().DateTime), 0)
{
}
Run Code Online (Sandbox Code Playgroud)