1
我一直在阅读有关不可变类型的内容,以及它如何不被推荐使用可变结构。适用于类的不变性
如果我有一个类来代替:
public class Vector
{
public double X, Y;
public void Rotate(double angle)
{
double x = this.X; double y = this.Y;
this.X = (float)((Math.Cos(angle) * x) - (Math.Sin(angle) * y));
this.Y = (float)((Math.Sin(angle) * x) + (Math.Cos(angle) * y));
}
}
因此,这将被称为:
Vector v = new Vector(1,0);
v.rotate(Math.PI/2.0);
在这种情况下,应该我已经写成这样?
public class Vector
{
public double X, Y;
public Vector Rotate(double angle)
{
double x = this.X; double y = this.Y;
return new Vector((float)((Math.Cos(angle) * x) - (Math.Sin(angle) * y)), (float)((Math.Sin(angle) * x) + (Math.Cos(angle) * y)));
}
}
要被称为:
Vector v = new Vector(1,0);
Vector v2 = v.rotate(Math.PI/2.0);
取决于你的使用情况 - 如果它只是不变性,然后是的,当然,你需要第二个版本 - 是确定你应该将'X'和'Y'标记为'readonly'(或者至少只提供公共获得者) – Carsten