有没有更好的方法来做我正在做的事情:
class Sample {
int SampleValueX, SampleValueY;
string SampleFacing;
public Sample(int samplevaluex, string samplefacing)
{
SampleValueX = startpositionx;
SampleValueY = 0;
SampleFacing = samplefacing;
}
public Sample(int samplevaluey, string samplefacing)
{
SampleValueX = 0;
SampleValueY = startpositionx;
SampleFacing = samplefacing;
}
}
这甚至被称为构造函数重载吗?如果我错了,请纠正我。
最佳答案
您可以使用可选参数
class Sample {
int SampleValueX, SampleValueY;
string SampleFacing;
public Sample(string samplefacing, int samplevaluex = 0, int samplevaluey = 0)
{
SampleValueX = samplevaluex;
SampleValueY = samplevaluey;
SampleFacing = samplefacing;
}
}
请注意,可选参数必须出现在必选参数之后