Oip*_*oks 1 c# automatic-properties coordinates
我有以下具有自动属性的类:
class Coordinates
{
public Coordinates(int x, int y)
{
X = x * 10;
Y = y * 10;
}
public int X { get; set; }
public int Y { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
正如您从构造函数中看到的,我需要将值乘以 10。有没有办法在不删除自动属性的情况下做到这一点?
我尝试了以下操作,但不认为它会导致递归,然后一切都变得很顺利
public int X { get {return X;} set{ X *= 10;} }
Run Code Online (Sandbox Code Playgroud)
我想将值赋给 X 和 Y 乘以 10。
Coordinates coords = new Coordinates(5, 6); // coords.X = 50 coords.Y = 60
coords.X = 7; // this gives 7 to X but I would like it to be 70.
Run Code Online (Sandbox Code Playgroud)
为了使设置器像这样工作,您需要使用支持字段:
class Coordinates
{
public Coordinates(int x, int y)
{
X = x;
Y = y;
}
private int _x;
public int X
{
get { return _x; }
set { _x = value * 10; }
}
private int _y;
public int Y
{
get { return _y; }
set { _y = value * 10; }
}
}
Run Code Online (Sandbox Code Playgroud)
鉴于你的例子:
Coordinates coords = new Coordinates(5, 6); // coords.X = 50 coords.Y = 60
coords.X = 7; // this gives 70
Run Code Online (Sandbox Code Playgroud)
但是,我不建议您使用这样的设置器,因为它可能会导致混乱。最好有一个专门的方法来执行这种乘法。最后,您的代码将更具描述性和直观性。