Equality of objects in. net

Source: Internet
Author: User

This article from: http://www.cnblogs.com/XmNotes/archive/2011/06/23/2088341.html

 

The comparison between objects in. NET is seemingly simple and actually a little complicated. This is similar to the situation in the real world. No one is absolutely equal in reality, regardless of people or things. Only the relative attributes are consistent or belong to the same category, it may not be transparent for a lifetime. In. net, equality is not so unpredictable, but it is worth tasting.

When it comes to equality, the newbie first learns the equal operator = (some. net Language is single =), this is natural, the problem is that a lot of people have been working for a year or two, when it comes to equality or just think of operators, it is too one-sided.

Here, there are four types of tokens in the text, and there are also four equal comparisons in. net, respectively:= Operator,Object. Equals Method,Object. referenceequals Method,Equals method of object instance.

First, let's look at the two static methods of the object. Their logic is relatively simple. The referenceequals method compares whether two objects have the same reference, that is, whether the addresses on the stack are the same. It does not make sense for the value type. If a value type parameter appears in the parameter, false is returned. It is mainly used for testing. It is rarely used in actual application development and has a long method name. For the reference type, if the result of the method is true, the equality is the strictest, purest, and equivalent of a fake package, which means the two parameters are actually the same object, of course, no matter which other equal comparison method is used, true should also be returned.

The equals static method of an object is actually an extension of the Instance equals method. It adds null judgment and is suitable for comparing two objects that may be null references. For the value type, the function of the equals instance method is the same.

Let's look at =. The small operator we deal with every day is not that simple. As mentioned above, the differences between static methods of two objects are mainly in the value type and reference type. Generally, not all types have the same effect on the reference type = and referenceequals static methods. value types are distinguished here. For native value types, such as int, double, long, char, etc., = is to directly compare its values, and different types can be compared with each other, such as int and char, 'A' = 65 returns true; for general struct, ifCodeMedium definition = (also include! =) Operator, cannot be compared with =.

You can also define the = operator for the reference type to overwrite the comparison supported by CLR native. The most common type is the string type, which defines the = Operator and reasonably relaxed the equal conditions so that the string type can be compared by value like the native value type. The = operator of the string class is actually the directly called equals method that has been rewritten by itself.

The string class is the most common and special one. Most interviews will ask about the characteristics of string. Apart from immutable and memory resident mechanisms, other main features are equal and special.

Finally, let's talk about the instance equals method. This is a virtual method. It is a method that we often need to override according to business logic in application development. It is convenient to define and use operators. However, except for special cases such as string, it is better to set = to keep the default rule for the reference type, and let the equals method achieve the "value" in the business to be equal. If not overwritten, The equals method also compares object references.

For the value type, the implementation = operation is like an embellishment. If you want to implement equal comparison operations, you should first override the equals method (similarly, to achieve size comparison, you should first implement the icomparable interface, instead of implementing comparison operators). When the equals method inherited from the object is used for value type, it compares all fields of the two objects to true only when they are all equal. It is said that reflection is used, and the efficiency is very low. However, if it is low, why must it be overwritten first?

Because all. net Framework Key-value set, are compared using the equals instance method, so it actually becomes. net, whether it is a native type, structure or class instance, The equals method should be used as its standard equal comparison method, including the type we implement. The benefits of using the instance method can also be understood and more flexible. We can add some overloaded equals methods to declare different comparative prerequisites. Works with the default rewritten equals method to form a complete set of comparison rules to meet the complex and variable standards in reality.

When rewriting the equals method, the official recommendation is to rewrite the gethashcode method. If you don't use this type as the key-value set key, it doesn't matter.

In some cases, when the complexity is to overload the equals method, we need to define a function class dedicated to comparing equal .. NET framework already provides an interface system. collections. iequalitycomparer has several built-in implementations, such as stringcomparer and equalitycomparer. We may also wish to implement this interface by writing our own comparison classes. Of course, you don't have to worry about that much if you can use it. View. NET FrameworkSource code, You can find that many messy classes are used to compare equal, probably internal privileges.

At the end, you can summarize a table at a Glance:

method

Category

default class behavior

native class type

knot structure

different types

row indicates whether the row can be overwritten write

application field View

Object. equals

Static Method

Call the equals instance method

Equal Value

Field Values are equal

Yes

Yes

The parameter may be null.

Object. referenceequals

Static Method

References are equal

Returns false.

Returns false.

Not Allowed

Not Allowed

Test

=

Operator

References are equal

Equal Value

Must be defined before use

Not Allowed

Yes

Native type, simple business logic

Equals

Instance method

References are equal

The value and type are equal.

Field Values are equal

Yes

Yes

General Processing

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.