我有以下具有自动属性的类:
class Coordinates
{
public Coordinates(int x, int y)
{
X = x * 10;
Y = y * 10;
}
public int X { get; set; }
public int Y { get; set; }
}
从构造函数中您可以看到,我需要将值乘以10。是否仍然可以在不删除自动属性的情况下进行操作?
我尝试了以下内容,但没有想到它会导致递归,然后一切都变了。
public int X { get {return X;} set{ X *= 10;} }
我想将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.
为了使setter那样工作,您需要使用backing字段:
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; }
}
}
给出您的示例:
Coordinates coords = new Coordinates(5, 6); // coords.X = 50 coords.Y = 60
coords.X = 7; // this gives 70
但是,我不建议您使用这样的二传手,因为它可能导致混乱。最好有一个专门的方法来做这种乘法。最后,您的代码将更具描述性和直观性。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句