重载+/-一元运算符

Joa*_*nge 3 .net c# operators

当你重写 - 一元运算符时,对于一个不可变类型,你可以这样写:

public static Point3 operator - (Point3 p)
{
    return new Point3 (-p.X, -p.Y, -p.Z);
}
Run Code Online (Sandbox Code Playgroud)

但对于+一元运算符,您应该如何实现它?像这样:

public static Point3 operator + (Point3 p)
{
    return p;
}
Run Code Online (Sandbox Code Playgroud)

或者像这样:

public static Point3 operator + (Point3 p)
{
    return new Point3 (p);
}
Run Code Online (Sandbox Code Playgroud)

jjn*_*guy 7

无论哪种方式都没关系.您没有在两种方法中的任何一种中改变原始对象.

如果你打电话string.substring(0, string.length()),没有理由不能返回原始字符串.

您签署的具有不变性的唯一合同是,一旦创建了对象,它就不会改变.