【发布时间】: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