【问题标题】:Constructor Chaining, did I do it right?构造函数链接,我做对了吗?
【发布时间】:2014-10-19 16:46:49
【问题描述】:

我正在学习构造函数链接以减少冗余代码,只是想知道我是否掌握得当并且做得对。我在第三个构造函数中也需要 this.Name = restaurantName 吗?代码如下:

 public Restaurant()
    {
        this.Name = DefaultName;
        this.Chain = null;
        this.SeatingCapacity = MinSeats;
        this.Smoking = false;
        this.LastMonthSales = MinSales;
        this.LastMonthCosts = MinCosts;
        this.OpenDays = new List<DayOfWeek>();
    }

    public Restaurant(string restaurantName)
        :this()
    {
        this.Name = restaurantName;            
    }

    public Restaurant(string restaurantName, int capacity)
        :this(restaurantName)
    {            
        this.SeatingCapacity = capacity;            
    }

【问题讨论】:

  • 对我来说看起来是正确的。
  • 是的。不,您不需要在第三个构造函数中设置 restaurantName,因为它将在第二个构造函数中设置。
  • 是的,这是迄今为止正确的方法。顺便说一句,它也被称为constructor initializer

标签: c# constructor chaining


【解决方案1】:

您可以通过参数化主构造函数来简化这一点,然后为其他重载传入默认值:

public Restaurant(string restaurantName, int capacity)
{
    this.Name = restaurantName;
    this.Chain = null;
    this.SeatingCapacity = capacity;
    this.Smoking = false;
    this.LastMonthSales = MinSales;
    this.LastMonthCosts = MinCosts;
    this.OpenDays = new List<DayOfWeek>();
}

public Restaurant(string restaurantName) : this(restaurantName, MinSeats)
{}

public Restaurant() : this(DefaultName)
{}

【讨论】:

    猜你喜欢
    • 2010-09-23
    • 1970-01-01
    • 1970-01-01
    • 2015-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多