Four comparison functions of C #!

Source: Internet
Author: User
Tags comparison table
Quote: Http://blog.csdn.net/Knight94/archive/2006/08/11/1050901.aspx. NET has four functions such as sentence. Many people who see this headline will be skeptical. Indeed, it is. NET provides referenceequals, static equals, specific types of equals and the = = operator of these four-sentence functions.   But these four functions have a subtle relationship, and changing the implementation of one function affects the results of other functions.   The first thing to say is that the two static functions of object.referenceequals and Object.Equals, for both of them, do not need to be rewritten because they have done what they have to do. For object.referenceequals This static function, the function situation is as follows: Public static bool ReferenceEquals (object left, object right);This function is to determine whether two reference type objects point to the same address. With this description, the scope of its use is determined, that is, it can be manipulated only for reference types. For any value-type data operation, it returns false even if it is discriminated against itself.     This is mainly because when the function is called, the value type data is boxed, that is, for the following form.     int n = 10; Object.referenceequals (n, N); this is because for n This data is boxed two times, and the address after each boxing is different, causing object.referenceequals (n, N) The result is always false . For the first sentence function, there is nothing to expand, because itself has done a good job of it. For the second object.equals this static function, the form is as follows: Public Static Boolean Equals (object left, object right);   According to its analysis of the book, its approximate function code is as follows:     public static void Equals (object left, object right)     {       //Check Object Identity         if ( left = right)//includes two null             return true;          //Both null references handled above          if (left = null) | | (right = null))             return false;           return to left. Equals (right);    }   It can be said that object.equals this function to complete the operation, need to go through three steps, the first step is to be based on the object to the type of the implementation of the operator of the result; the second step is to determine whether NULL, as well as the first step , the execution result of the type = = operator is required, and the final step is to use the execution result of the Equals function of the type. In other words, the return result of this static function depends on the two-sentence function to be mentioned later. Whether the type provides the corresponding function of the sentence, becomes the important factor to return the result of this function.   So for object.equals this static method, although the type that accepts the parameter also belongs to the reference type, but differs from the Object.referenceequals function, for the following code, can obtain the correct result.     int n = 10;     Debug.WriteLine (String. Format ("{0}", Object.Equals (n, N));     Debug.WriteLine (String. Format ("{0}", Object.Equals (n, 10));   This is because in this function you want to use a specific type of two function, but in the function itself, the judgment is done, so do not need to overload add complex operations.   To better describe the remaining two functions, first explain the meaning of equivalence. The meaning of equivalence is reflexive, symmetric, and transitive. The so-called reflexive, that is, a = = A; and symmetry, is a = = B, then b = = A; pass is a = = B,b = c, then a = = C; Understand the equivalence meaning, then in the implementation of the type of the sentence function also satisfies this equivalence rule.   for two-sentence functions that can be overloaded, the first is to introduce the Equals function of the type, which is roughly the following: public override bool Equals (object right);   So what do you do with a type of equals, generally as follows:     public class KeyData     {         private int ndata;         public int Data         {             get{return Ndata}              set{ndata = value;}        }     & nbsp;     public override bool Equals (object right)         {& nbsp;          //check NULL              if (right = null)                  return false;              //check Reference EqualitY             if (object. ReferenceEquals (this, right))                  return true;              //check Type              if (this. GetType ()!= right. GetType ())                 return False              //convert to current type              KeyData Rightaskeydata = right as KeyData;              //check Members value              return this. Data = = Rightaskeydata.data;        }    } &nbsP Add a type check as above, i.e. if (this. GetType ()!= right. GetType ()) This part, this is because the subclass object can pass as Into the base class object, which causes different types of objects to be sentenced and so on, which violates the equivalence relation. In addition to the Equals function for the type, there is no limit to the type being a reference type, which can be overloaded for value types, but I do not recommend that the main argument type of the Equals function is immutable, that is, by this method, the value type is boxed.   And this is a more effective effect. For value types, I recommend the last type of function, the overloaded operator = = function, which is the approximate form of the following: Public static BOOL operator = = (KeyData left, KeyData right);   for a value type, its approximate form should be as follows:     public struct KeyData     {    & nbsp;   private int ndata;         public int Data         {             get{return Ndata}              set{ndata = value;}        }     & nbsp;     public static bool operator = = (KeyData left, keydata right)    &nbsp ;    {            return left. Data = right. Data;        }           public static bool Operator!= (KeyData left, KeyData right)         {     & Nbsp;      return to left. Data!= right. Data;        }    }   because = = operation and!= action to synchronize the definition, so in the definition = = when overloading a function, you also define the!= overloaded functions. This is also. Net maintain consistency in the operation of the contract. So for the last function, the overloaded operator method does not fit the reference type. This is. Net regular phenomenon, to judge two reference types, do not use = = , but to use the equals of an object function. So keep this style when writing your own type. So for the above four kinds of sentence function, will produce the following similar comparison table. object.equals The result of the td>
  operation depends on the Scope Recommendation
object.referenceequals two parameters Object is part of the same reference reference type do not use it to determine value type data
parameter type self-sentence function unrestricted test Effect of boxed operations on value type data
type equals type overloaded functions Unrestricted Consider the effect of boxing operations on value type data
Type = = overload type overloaded function Unrestricted do not overload this operator in reference types
So in the writing type sentence function, what to pay attention to, give the following suggestions.   First of all, to determine whether the current definition of the type has the meaning of the sentence, and secondly, the definition of the type of the sentence function to meet the equivalence rules; Finally, it is best not to overload the definition of the Equals function, and the reference type is best not to overload the definition = = operator. Summary: object.refererce.equals comparison reference equals (object) compare references and values (not NULL, type to be the same) equals (object Aobject b) if Obja Is the same instance as OBJB, or if both are null references, or if Obja.equals (OBJB) returns true, then the true; otherwise the false。 = = value, which can also be used to determine whether the reference is also equal to String = = is to judge value and overload the Equals, to Judgment value
Related Article

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.