C# 3.0 - 对象初始值设定项

标签 c# .net-3.5

我遇到了一个小问题,我不明白为什么,很容易绕过它,但我仍然想了解。

我有以下类(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/

相关文章:

c# - EntityFramework 6 不适用于 MySql

c# - 使用 Linq To Objects 执行分组/投影的最简单方法

c# - 与数据库保持同步

c# - 流利的 NHibernate : Cascade delete from one side only on Many-to-Many relationship

c# - 十进制值被识别为 DateTime,而不是从 DateTime.Parse 返回 false

c# - 安装过程中如何创建文件夹?

c# - 如何检查队列是否为空?

c++ - DLL 存在时出现 System.DLLNotFoundException

c# - 配置缓存类与使用 HTTP header 缓存

c# - 创建断开连接的数据库应用程序的最佳基于 .NET3.5 的策略