今天终于又写了一死循环程序。深深的陷入了操作符重载这个陷阱。
代码如下:
public class Line : ICloneable

{
private Point2D endPoint;
private Point2D startPoint;

private Line()
: this(Point2D.Empty, Point2D.Empty)

{
}

public Line(Point2D startPoint, Point2D endPoint)

{
this.startPoint = startPoint;
this.endPoint = endPoint;
}

public object Clone()

{
return new Line(this.startPoint, this.endPoint);
}

public override bool Equals(object obj)

{
if (obj != null)

{
if (!(obj is Line))
return false;
Line line = (Line)obj;
if (this.startPoint.Equals(line.startPoint))
return this.endPoint.Equals(line.endPoint);
}
return false;
}

public static bool operator ==(Line line1, Line line2)

{
if (line1 == null && line2 == null)
return true;
if (line1 != null && line2 != null)
return line1.Equals(line2);
return false;
}

public static bool operator !=(Line line1, Line line2)

{
if (line1== null && line2==null)
return false;
if (line1 != null && line2 != null)
return !line1.Equals(line2);
return true;
}


public static Line Empty

{
get

{
return new Line(Point2D.Empty, Point2D.Empty);
}
}

[Browsable(false)]
public bool IsEmpty

{
get

{
return startPoint.IsEmpty ? endPoint.IsEmpty : false;
}
}
}
这个一个描述一根线条的类,这段代码怎么编译都不会出错。但请大家留意中间的这段代码:

public static bool operator ==(Line line1, Line line2)

{
if (line1 == null && line2 == null)
return true;
if (line1 != null && line2 != null)
return line1.Equals(line2);
return false;
}

public static bool operator !=(Line line1, Line line2)

{
if (line1== null && line2==null)
return false;
if (line1 != null && line2 != null)
return !line1.Equals(line2);
return true;
}
这就是个不折不扣的死循环,而且是死得很惨的那种。
如果你在某个地方使用了如下形式的代码,不死循环都很难。
Line line1 = new Line();
Line line2 = new Line();
if (line1==line2)

{
}
要想解决上面的问题,必须把代码改成如下形式:
public static bool operator ==(Line line1, Line line2)

{
if (object.Equals(line1, null) && object.Equals(line2, null))
return true;
if (!object.Equals(line1, null) && !object.Equals(line2, null))
return line1.Equals(line2);
return false;
}

public static bool operator !=(Line line1, Line line2)

{
if (object.Equals(line1, null) && object.Equals(line2, null))
return false;
if (!object.Equals(line1, null) && !object.Equals(line2, null))
return !line1.Equals(line2);
return true;
}
不过这里line是一个class,如果是struct,不知会这么样。还没试过呢。
代码如下:





















































































































如果你在某个地方使用了如下形式的代码,不死循环都很难。



























