C# 构造函数链接,我做得对吗?
我正在学习构造器链接以减少冗余代码,我只是想知道我是否有一个像样的掌握并做得对。在第三个构造函数中也需要这个.Name=restaurantName吗?代码如下:C# 构造函数链接,我做得对吗?,c#,constructor,chaining,C#,Constructor,Chaining,我正在学习构造器链接以减少冗余代码,我只是想知道我是否有一个像样的掌握并做得对。在第三个构造函数中也需要这个.Name=restaurantName吗?代码如下: public Restaurant() { this.Name = DefaultName; this.Chain = null; this.SeatingCapacity = MinSeats; this.Smoking = false; th
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;
}
公共餐厅()
{
this.Name=DefaultName;
this.Chain=null;
此。座位容量=分钟座位;
这个。吸烟=假;
this.LastMonthSales=MinSales;
this.LastMonthCosts=MinCosts;
this.OpenDays=新列表();
}
公共餐厅(string restaurantName)
:此()
{
this.Name=restaurantName;
}
公共餐厅(字符串餐厅名称,国际容量)
:此(餐厅名称)
{
这个。座位容量=容量;
}
您可以通过参数化主构造函数,然后为其他重载传递默认值来简化此过程:
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)
{}
公共餐厅(字符串餐厅名称,内部容量)
{
this.Name=restaurantName;
this.Chain=null;
这个。座位容量=容量;
这个。吸烟=假;
this.LastMonthSales=MinSales;
this.LastMonthCosts=MinCosts;
this.OpenDays=新列表();
}
公共餐厅(string restaurantName):此(restaurantName,MinSeats)
{}
公共餐厅():此(默认名称)
{}
您可以通过参数化主构造函数,然后为其他重载传递默认值来简化此过程:
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)
{}
公共餐厅(字符串餐厅名称,内部容量)
{
this.Name=restaurantName;
this.Chain=null;
这个。座位容量=容量;
这个。吸烟=假;
this.LastMonthSales=MinSales;
this.LastMonthCosts=MinCosts;
this.OpenDays=新列表();
}
公共餐厅(string restaurantName):此(restaurantName,MinSeats)
{}
公共餐厅():此(默认名称)
{}
在我看来是正确的。是的。不,您不需要在第三个构造函数中设置restaurantName
,因为它将在第二个构造函数中设置。是的,这是迄今为止正确的方法。顺便说一句,它也被称为构造函数初始值设定项
在我看来是正确的。不,您不需要在第三个构造函数中设置restaurantName
,因为它将在第二个构造函数中设置。是的,这是迄今为止正确的方法。顺便说一句,它也被称为构造函数初始值设定项