2015-05-24 34 views
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); 
+2

取决于你的使用情况 - 如果它只是不变性,然后是的,当然,你需要第二个版本 - 是确定你应该将'X'和'Y'标记为'readonly'(或者至少只提供公共获得者) – Carsten

回答

3

是的,不可改变的类将当你创建一个新的版本,返回一个新的实例。例如,这就是所有String方法的工作原理。

但是,您还应该确保不能从外部更改属性。此外,没有理由向下投射的坐标float当属性double

public class Vector 
{ 

    public double X { get; private set; } 
    public double Y { get; private set; } 

    public Vector(double x, double y) 
    { 
     X = x; 
     Y = y; 
    } 

    public Vector Rotate(double angle) 
    { 
     double x = this.X; double y = this.Y; 
     return new Vector(((Math.Cos(angle) * x) - (Math.Sin(angle) * y)), ((Math.Sin(angle) * x) + (Math.Cos(angle) * y))); 
    } 
}