Recently, I encountered an equal operator overload problem during programming. This is a trap of C.
The Coordinate class I defined originally used to overload the equality operator as follows:
Publice class Coordinates
{
....
Public override bool Equals (object obj)
{
If (! (Obj is Coordinates) return false;
Coordinates other = (Coordinates) obj;
Return (this. longwheel. CompareTo (other. longwheel) = 0) & (this. latitude. CompareTo (other. latitude) = 0 );
}
Public static bool operator = (Coordinates lhs, Coordinates rhs)
{
Return lhs. Equals (rhs );
}
Public static bool operator! = (Coordinates lhs, Coordinates rhs)
{
Return! (Lhs = rhs );
}
...
}
This is often seen in the case of operator overloading, but there are some problems when using it: that is, when a Coordinate object is NULL and it is compared with NULL, It is shown as follows:
Coordinates actualPos = null;
If (actualPos = null)
{... }
Else
{... }
An error is thrown during runtime, prompting that a pointer is null. The trace result shows that there is a problem with the "=" Operator. It calls the "lhs. Equals (rhs)" Statement and the result is that the lhs itself does not exist, causing an exception.
Therefore, I tried to exclude this situation before calling this statement, so I changed the overload function:
Public static bool operator = (Coordinates lhs, Coordinates rhs)
{
If (lhs = null) return (rhs = null );
Return lhs. Equals (rhs );
}
The result shows that this function will continue to call itself, and then the exception still occurs.
To solve this problem, we must break this endless loop and try to map lhs to object, as shown below:
Public static bool operator = (Coordinates lhs, Coordinates rhs)
{
If (lhs as object) = null) return (rhs as object) = null );
Return lhs. Equals (rhs );
}
After the lhs is mapped to "=" after the object, the equal operator of the object is used, and the result is naturally OK. I believe that the use of C # programming will sooner or later, and it may be inexplicable. I hope the above articles will be useful to you.