我时不时地碰到我以前见过的语法,但从未使用过.这是其中一次.
有人可以按照C#构造函数方法解释":this"或":base"的用途吗?
例如:
public MyClass(SomeArg arg) : this(new SomethingElse(), arg)
{
}
Run Code Online (Sandbox Code Playgroud)
我的直觉是它用于将默认参数映射到另一个构造函数方法.
下面是一个struct名为Complex 的构造函数,它有两个成员变量,Real和Imaginary:
public Complex(double real, double imaginary) : this()
{
Real = real;
Imaginary = imaginary;
}
Run Code Online (Sandbox Code Playgroud)
函数头中冒号后的部分有什么用?
我无法阅读这行代码
public Wine (decimal price, int year) : this (price) { Year = year; }
Run Code Online (Sandbox Code Playgroud)
什么: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;
}
}
Run Code Online (Sandbox Code Playgroud)