Static void main (string [] ARGs)
{
Test T = new test ();
T. myfun ();
Console. Readline ();
}
Class Test
{
// The custom method is used to test the overload operator.
Public void myfun ()
{
Test T = new test ();
If (t = NULL) console. writeline ("t is blank! ");
Console. writeline ("t is not empty! ");
}
// Reload the equal Operator
Public static bool operator = (test T1, test T2)
{
Return t2.equals (T1 );
}
// Overload unequal Operators
Public static bool Operator! = (Test T1, test T2)
{
Return! (T1 = t2 );
}
// Override the hashcode Method
Public override int gethashcode ()
{
Return base. gethashcode ();
}
// Rewrite the equals Method
Public override bool equals (Object OBJ)
{
Return base. Equals (OBJ );
}
}
Analysis: T2 is found to be empty during debugging. When the program determines whether the value of the referenced variable t is null or not, the equal operator is used, and the method corresponding to the overloaded equal operator is called, in this way, T and null will be passed in as parameters of the method, and null will be passed to parameter T2, And the overload method will also call this method, which is an endless loop.
Solution:
Public static bool operator = (test T1, test T2)
{
If (t2 as object) = NULL)
{
Return (T1 as object) = NULL;
}
Else
{
Return t2.equals (T1 );
}
}
Equal operator overload trap