我正在学习构造函数链接以减少冗余代码,并且只是想知道我是否有一个正确的把握并且做得对。我是否还需要第三个构造函数中的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;
}
答案 0 :(得分:4)
您可以通过参数化主构造函数来简化这一点,然后传递其他重载的默认值:
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)
{}