Is there a difference in the order of equality?
Or in short, is the second op开发者_开发知识库erator needed?
public static bool operator ==(Vector3 v, float scalar)
{
return v.X == scalar && v.Y == scalar && v.Z == scalar;
}
public static bool operator ==(float scalar, Vector3 v)
{
return v == scalar;
}
Yes, it is needed if you want to allow asymmetric equality tests:
bool foo = (yourVector3 == 5); // requires the first version
bool bar = (5 == yourVector3); // requires the second version
Without the first version you'd get a compile-time error saying something like "Operator '==' cannot be applied to operands of type 'Vector3' and 'int'". Without the second version the error would say something like "Operator '==' cannot be applied to operands of type 'int' and 'Vector3'".
There is from the developer's expectation that equality is commutative e.g. if you do a == b that b==a is also valid. Because of this it would be confusing if you did one and it worked and then reversed it and you got the following error.
Operator '==' cannot be applied to operands of type 'float' and 'Vector3'
But strictly speaking no you don't have to. It would just smell really bad.
精彩评论