C # Learning Notes-----= = and equals

Source: Internet
Author: User

http://blog.csdn.net/wuchen_net/article/details/5409327

Http://www.cnblogs.com/chen0720/p/3209398.html

1. ReferenceEquals, = =, Equals
Equals, = =, referenceequals can be used to determine whether an individual of two objects is equal.

A) ReferenceEquals
ReferenceEquals is a static method of object that compares an object of two reference types to a reference to the same object. It always returns false for value types. (Because box after the object is always different, hehe)

b) = = is a two-dollar operator that can be overloaded to compare two objects for equality.
For built-in value types, = = Determines whether the generation values of two objects are equal. It automatically makes the necessary type conversions as needed, and returns TRUE or false based on whether the values of two objects are equal. For example:

Int a = 100;
Double b = 100;

If (A = = b)
Console.WriteLine ("Equal supports compare between different types!");

The above program will output:
Equal supports compare between different types!

For user-defined value types, if the = = operator is not overloaded, = = will not be able to be used. For example:


Struct Userstruct1;
Userstruct1 A;
Userstruct1 b;

If (A = = b)
Console.WriteLine ("Can = = reach this far?")

The above code is not capable of compiling. You can use overloading to make = = Work on user-defined value types.

For reference types, = = The default behavior is the same as referenceequals, with only two objects returning true when they point to the same reference. However, many classes in the. NET Framework overload = =, for example, the = = of the string class behaves the same as equals, judging whether the contents of the two strings are equal. Therefore, in an application, the = = operator is not recommended for system-defined reference types, so that the program will not have a different running result than expected.

c) equals as an object built-in method, equals supports comparisons for any two Ctscommon Type system objects.
equals it has a static method and a version that can be overloaded, the following program fragment explains the use of these two methods,

int a = 5;
int b = 5;

If (Object.Equals (A, B))
can also use if (A.equals (b))
{
Console.WriteLine ("A is equal to B");
}

In fact, the results of these two versions are identical, and if the user overloads equals, the call is the equals after the user overloads. The benefit of the static method of equals is that the object used for comparison can be considered null.

The Equals method has different definitions for value types and reference types, the same type for value types, and the same values (which must be the same for each member of a struct), and equals returns True, otherwise false. For reference types, the default behavior is the same as referenceequals, with only two objects returning true when they point to the same reference. equals can be overloaded as needed, such as the Equals of the string class to determine whether the contents of two strings are equal.

StringBuilder class

Represents a variable character string. This class cannot be inherited.


StringBuilder a = new StringBuilder ();
A.append ("The Test a");
String S1 = a.tostring ();
String s2 = "the test a";

if (S2 = = S1)
Console.WriteLine ("= = Returns true");

if (Object.Equals (S2, S1))
{
Console.WriteLine ("Equals returns true");
}

if (object.referenceequals (S2, S1))
{
Console.WriteLine ("ReferenceEquals Returns True");
}

This instance will output:
= = Returns True
equals returns True

Note: For the string class, directly declare S1 = "The test a", the output will contain "ReferenceEquals returns True",
Because of the default, string retains only one copy on the heap for the same string declared, so S1 and S2 will point to the same reference

Http://javasky.bloghome.cn/posts/142567.html

After discussing the operators and briefly describing the equals operator, you should consider what equality means when dealing with instances of classes and structs. The mechanism for understanding object equality comparisons is important for writing logical expressions, and is also important for implementing operator overloading and data type conversions, and operator overloading is discussed later in this chapter.

The Mechanism for object equality comparisons is different for comparisons of reference types (instances of classes) and for value types (base data types, instances of structs or enumerations). The following describes equality comparisons for reference types and value types, respectively.

5.3.1 Equality Comparison of reference types

One surprising aspect of System.Object is that it defines 3 different methods to compare the equality of objects: two versions of ReferenceEquals () and Equals (). Plus the comparison operator = =, there are actually 4 ways to do equality comparisons. These methods have some subtle differences, as described below.

================================================================

The following are the most obvious

1. ReferenceEquals () method

ReferenceEquals () is a static method that tests whether two references point to the same instance of the class, that is, whether two references contain the same address in memory. As a static method, it cannot be overridden, so only the System.Object implementation code can be used. If the supplied two references point to the same object instance, ReferenceEquals () always returns TRUE, otherwise it returns false. However, it considers null equal to NULL:

SomeClass x, y;

x = new SomeClass ();

y = new SomeClass ();

BOOL B1 = ReferenceEquals (null, NULL); return True

BOOL B2 = ReferenceEquals (null, x); return False

BOOL B3 = ReferenceEquals (x, y); return false because X and Y

Point to different objects

2. The virtual Equals () method

The System.Object implementation code for the Equals () virtual version also compares references. But because this method is virtual, you can override it in your own class and compare objects by value. In particular, if you want an instance of a class to be used as a key in a dictionary, you need to override this method to compare values. Otherwise, depending on how Object.GetHashCode () is overridden, the dictionary class that contains the object either does not work or works very inefficiently. When overriding the Equals () method, be aware that the overridden code does not throw an exception. This is because if an exception is thrown, the dictionary class will have a problem, and some internally call this method. NET base class can also be problematic.

3. Static Equals () method

The static version of Equals () has the same effect as the version of the virtual instance, except that the static version has two parameters and compares them equally. This method can handle a case where one of the two objects is null, so if an object could be null, this method can throw an exception and provide additional protection. The statically overloaded version first checks whether the reference it transmits is null. Returns true if they are all null (because NULL is equal to NULL). Returns False if only one reference is null. If two references point to an object, it calls the virtual instance version of Equals (). This means that when overriding the instance version of Equals (), the effect is equivalent to rewriting the static version as well. [Page]

4. Comparison operator = =

It is a good idea to treat comparison operators as intermediate options between strict value comparisons and strict reference comparisons. In most cases, the following code:

BOOL B = (x = = y); x, Y object references

Represents a comparison reference. However, if you think of some classes as values, their meanings are more intuitive. In these cases, it is best to override the comparison operator to perform a comparison of the values. The overloads of the operators are discussed later, but obviously one example of this is the System.String class, which Microsoft overrides to compare the contents of the strings rather than their references.

Equality Comparison of 5.3.2 value types

When you make an equality comparison of a value type, the same rule as the reference type: ReferenceEquals () is used to compare references, Equals () is used to compare values, and the comparison operator can be thought of as an intermediate item. But the big difference is that value types need to be boxed before they can be converted to references to execute methods on them. In addition, Microsoft has overloaded the instance method equals () in the System.ValueType class to allow for appropriate equality testing of value types. If you call Sa.equals (SB), where SA and SB are instances of a struct, return true or false depending on whether the SA and SB contain the same value in all of their fields. On the other hand, by default, the = = operator cannot be overloaded on its own structure. The use of (SA==SB) in an expression results in a compilation error unless an overloaded version of = = is provided for the structure in code.

In addition, ReferenceEquals () always returns false when applied to value types, because value types need to be boxed into an object in order to call this method. Even if you use the following code:

BOOL B = ReferenceEquals (V, v); V is a variable of some value type

Also returns false, because when each parameter is converted, V is boxed separately, which means that a different reference is obtained. It doesn't really make sense to call ReferenceEquals () to compare value types.

Although the Equals () default overload provided by System.ValueType is certainly sufficient to handle most custom structures, it can still be overridden for its own structure to improve performance. Also, if a value type contains a reference type as a field, you need to override Equals () to provide the appropriate semantics for these fields, because the default rewrite version of Equals () only compares their addresses.

Http://www.zxbc.cn/html/20070809/25909.html

=============================================================================================================== =====

Http://msdn.microsoft.com/zh-cn/library/bsc2ak47 (vs.80). aspx

Object.Equals Method (Object)

Determines whether the specified object is equal to the current object.

Parameters
Obj

objectthat is compared to the current object.

return value

trueif the specified object is equal to the current object; otherwise false.

Note

The default implementation of Equals only supports reference equality, but derived classes can override this method to support value equality.

For reference types, equality is defined as object equality, that is, whether the references refer to the same object. For value types, equality is defined as bitwise equality. The ValueType class supports value types.

Note to the implementation this method can be overridden by a derived class. For example, if two objects represent the same value, many base data types return true, otherwise falseis returned. This method only compares primitives and objects. To compare a more complex structure, such as an object array, you must override the method. The following statement must be true for all implementations of the Equals method. In the list, x, y, and z represent an object reference that is not a null reference (Nothing in Visual Basic).

    • X.equals (x) returns truein addition to cases involving floating-point types. See IEC 60559:1989, Binary floating-point arithmetic for microprocessor Systems.

    • X.equals (y) returns the same value as Y.equals (x).

    • If both x and Y are NaN, x.equals (y) returns true.

    • When and only if X.equals (z) returns true , (X.equals (y) && y.equals (z)) returns true.

    • Successive calls to X.equals (y) return the same value as long as the objects referenced by x and Y are not modified.

    • X.equals (null reference (Nothing in Visual Basic)) returns false.

About belonging to EqualsSee GetHashCode For additional required behavior for the method. EqualsImplementation must not throw an exception. For some types of objects, it is best to let EqualsTest for value equality instead of reference equality. If two objects have the same value, even if they are not the same instance, the EqualsImplementation still returns true。 The type implementers determine the composition of the "value" of an object, but this is usually some or all of the data stored in an instance variable of an object. For example, the value of string is based on string characters, and for two string instances that contain exactly the same characters in the same order, StringClass of Equalsmethod returns true。 The type of implementation IComparable must be overridden Equals。 Rewrite EqualsType must also be overridden by the GetHashCodeOtherwise, Hashtable may not work correctly. If the programming language supports operator overloading, and you choose to overload the equality operator for a given type, the type must override the EqualsMethod. Such a EqualsThe method implementation must return the same result as the equality operator. Following this guideline helps ensure that the use of EqualsClass library code (such as ArrayList and Hashtable) behaves in a manner consistent with the equality operators used by the application code. The following are guidelines for implementing value types:
    • Consider overriding equalsin order to achieve performance-enhancing performance on ValueType than the default implementation of Equals .

    • If you override Equals and the language supports operator overloading, you must overload the equality operator for the value type.

The following are guidelines for implementing reference types:
  • If the semantics of a reference type are based on the fact that the type represents some (some) value, consider overriding Equalsfor that type.

  • Even if most reference types override Equals, they must not overload the equality operator. However, if you implement a reference type that wants to have value semantics (such as a complex number type), you must override the equality operator.

  • Using System;

    public class Sample {
    void Method () {
    Object Obj1 = new Object ();
    Object Obj2 = new Object ();
    Console.WriteLine (Obj1.equals (OBJ2)); ===> false
    Obj2 = Obj1;
    Console.WriteLine (Obj1.equals (OBJ2)); ===> true
    }
    }

    ===================================================

    Object.Equals method (object, Object)

    Determines whether the specified Object instance is considered equal.

    Parameters
    Obja

    The first Object to compare.

    Objb

    The second Objectto compare.

    return value

    If obja is the same instance as OBJB , or if both are null references, or if obja.equals (OBJB) returns true; True, otherwise false.

    Note

    The default implementation of Equals only supports reference equality, but derived classes can override this method to support value equality.

    For reference types, equality is defined as object equality, that is, whether the references refer to the same object. For value types, equality is defined as bitwise equality. The ValueType class supports value types.

    Before calling Obja.equals (OBJB) , this method first checks whether all two parameters are null references.

    Example

    The following code example compares different objects.

    C#
    Copy Code

  • [C-sharp]View Plaincopy
    1. Using System;
    2. Public class MyClass {
    3. public static void Main () {
    4. string S1 = "Tom";
    5. string s2 = "Carol";
    6. Console.WriteLine ("Object.Equals (/" {0}/",/" {1}/") + = {2}",
    7. S1, S2, object.equals (S1, S2));
    8. S1 = "Tom";
    9. S2 = "Tom";
    10. Console.WriteLine ("Object.Equals (/" {0}/",/" {1}/") + = {2}",
    11. S1, S2, object.equals (S1, S2));
    12. S1 = null;
    13. S2 = "Tom";
    14. Console.WriteLine ("Object.Equals (NULL,/" {1}/") + = {2}",
    15. S1, S2, object.equals (S1, S2));
    16. S1 = "Carol";
    17. S2 = null;
    18. Console.WriteLine ("Object.Equals (/" {0}/", null) + = {2}",
    19. S1, S2, object.equals (S1, S2));
    20. S1 = null;
    21. S2 = null;
    22. Console.WriteLine ("object.equals (null, NULL) + = {2}",
    23. S1, S2, object.equals (S1, S2));
    24. }
    25. }/* 
    26. This code produces the following output.
    27. Object.Equals ("Tom", "Carol") = False
    28. Object.Equals ("Tom", "Tom") = True
    29. Object.Equals (NULL, "Tom") = False
    30. Object.Equals ("Carol", null) = False
    31. Object.Equals (null, NULL) = True
    32. */

  • Object.referenceequals method

    Determines whether the specified Object instance is the same instance.


    Parameters
    Obja

    The first Object to compare.

    Objb

    The second Objectto compare.


    return value
  • True if obja is the same instance as objb , or falseif both are null references.

    Example

    The following code example uses referenceequals to determine whether two objects are the same instance.

  • [C-sharp]View Plaincopy
    1. Using System;
    2. Class MyClass {
    3. static void Main () {
    4. object o = null;
    5. object p = null;
    6. Object q = new Object ();
    7. Console.WriteLine (Object.referenceequals (O, p));
    8. p = q;
    9. Console.WriteLine (Object.referenceequals (P, q));
    10. Console.WriteLine (Object.referenceequals (O, p));
    11. }
    12. }
    13. /*
    14. This code produces the following output.
    15. True
    16. True
    17. False
    18. */

C # Learning Notes-----= = and equals

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.