gpt4 book ai didi

c# - 构造函数重载和类参数

转载 作者:行者123 更新时间:2023-11-30 13:12:09 29 4
gpt4 key购买 nike

有没有更好的方法来做我正在做的事情:

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;
}

}

注意可选参数必须出现在必选参数之后

关于c# - 构造函数重载和类参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13839327/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com