我看不懂这行代码
public Wine (decimal price, int year) : this (price) { Year = year; }
:this
关键字在构造函数中的作用
public class Wine
{
public decimal Price;
public int Year;
public Wine (decimal price)
{
Price = price;
}
public Wine (decimal price, int year) : this (price)
{
Year = year;
}
}
答案 0 :(得分:5)
这称为构造函数链接。您只需调用它,而不是重写单参数构造函数的代码。 C#通过使用带冒号的简短表示法来简化这一点。
答案 1 :(得分:3)
this(price)
调用另一个构造函数,在这种情况下只接受一个十进制类型的参数。作为参考阅读"Using Constructors"。
我不是这个特定示例的忠实粉丝,因为两个构造函数都进行了初始化工作。
在我看来,最好将默认值传递给一个构造函数,然后执行 all 工作 - 这样初始化不会在不同的构造函数之间传播,并且您有一个单独的位置,其中所有内容都已初始化 - 更好的方法是:
public class Wine
{
public decimal Price;
public int Year;
public Wine (decimal price): this(price, 0)
public Wine (decimal price, int year)
{
Price = price;
Year = year;
}
}
答案 2 :(得分:0)
首先使用单个小数参数价格调用构造函数。
答案 3 :(得分:0)
它调用具有该签名的同一个类中的另一个构造函数,将值传递给它,并将其提供给初始构造函数调用。在您的示例中,Wine类具有(至少)两个构造函数,一个采用decimal
(价格)和int
(年),另一个只采用{{{ 1}}(价格)。
当您调用带有两个参数的那个参数时,它会调用只接受一个参数的参数将值传递给第二个参数。然后它执行构造函数体(设置Year to year)。
这允许您重用应该发生的公共逻辑,无论进行哪个构造函数调用(在这种情况下设置价格应该总是发生,但更具体的构造函数也设置Year)。