For a long time, when implementing object determination and so on, after writing the Equals method, we habitually reload = and! = Operator, as follows,
Code 1:
1 /// <summary>
2 // overload equal Operators
3 /// </summary>
4 public static bool operator = (MyObject lhs, MyObject rhs)
5 {
6 return lhs. Equals (rhs );
7}
8 /// <summary>
9 // overload unequal Operators
10 /// </summary>
11 public static bool operator! = (MyObject lhs, MyObject rhs)
12 {
13 return! (Lhs. Equals (rhs ));
14}
15
Recently, it was suddenly found that this writing method has a hidden risk that we will first determine whether the object is null before performing operations on the object,
Code 2:
1 if (myobject = null)
2 {
3 // do something
4}
5
If myobject is null! = When the operator finally calls the Equals method of the current object, a classic error is thrown in line 1 of code 1:
"The object reference is not set to the instance of the object ."
I checked Programming C # and found that the overload = operator should call the Equals static method of the Object class, corresponding! = Is also called = and then returns the reverse:
Code 4:
1 /// <summary>
2 // overload equal Operators
3 /// </summary>
4 public static bool operator = (MyObject lhs, MyObject rhs)
5 {
6 return Object. Equals (lhs, rhs); // call the Equals method of the Object class
7}
8 /// <summary>
9 // overload unequal Operators
10 /// </summary>
11 public static bool operator! = (MyObject lhs, MyObject rhs)
12 {
13 return! (Lhs = rhs); // call =, reverse
14}
The static Equals method of the Object class is as follows:
Code 5:
1 public static Boolean Equals (Object objA, Object objB)
2 {
3 // If objA and objB point to the same object, true is returned. Including null = null.
4 if (objA = objB) return true;
5 // If either objA or objB is null, false is returned.
6 if (objA = null) | (objB = null) return false;
7 // call the Equals method.
8 return objA. Equals (objB );
9}
The Code shows that this method can handle the case where myobject is null.
Therefore, when the = Operator is overloaded, The Equals () method of the current class should not be called, but the Object. Equals (object objA, object objB) static method should be called.