我有一个矢量类,它的Equals(object obj)
方法被覆盖,以便我可以比较它们。
public class Vector3f
{
public float x,y,z;
public Vector3f(float x, float y, float z)
{
this.x = x;
this.y = y;
this.z = z;
}
public static Vector3f operator +(Vector3f a, Vector3f b) {
return new Vector3f(a.x + b.x, a.y + b.y, a.z + b.z);
}
public static Vector3f operator -(Vector3f a, Vector3f b) {
return new Vector3f(a.x - b.x, a.y - b.y, a.z - b.z);
}
public override bool Equals(object obj)
{
Vector3f other = (Vector3f)obj;
return x == other.x && y == other.y && z == other.z;
}
public override string ToString()
{
return String.Format("<{0},{1},{2}>",x,y,z);
}
}
加号运算符在我的单元测试中按预期工作。但是,当我减去两个向量时,它说它们不相等
Test 'RTTests.Testies.vector_subtraction_works' failed:
Expected: <<1.1,0.1,0.1>>
But was: <<1.1,0.1,0.1>>
Testies.cs(60,0): at RTTests.Testies.vector_sub_works()
我不确定为什么比较适用于加法而不是减法,特别是因为两种情况下的输出值相同?
编辑:我对此的测试
[Test]
public void vector_addition_works()
{
Vector3f v1 = new Vector3f(1.0f, 1.0f, 1.0f);
Vector3f v2 = new Vector3f(1.6f, 3.2f, 4.7f);
Vector3f expected = new Vector3f(2.6f, 4.2f, 5.7f);
Vector3f actual = v1 + v2;
Assert.AreEqual(actual, expected);
}
[Test]
public void vector_sub_works()
{
Vector3f v1 = new Vector3f(1.1f, 1.1f, 1.1f);
Vector3f v2 = new Vector3f(0.0f, 1.0f, 1.0f);
Vector3f expected = new Vector3f(1.1f, 0.1f, 0.1f);
Vector3f actual = v1 - v2;
Assert.AreEqual(actual, expected);
}