Equal operator overload trap

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.