Comparing reference types for equality in C#
System.Object defines three different methods for comparing objects
for equality: ReferenceEquals() and two versions of Equals(). Add to this the comparison operator (==), and there actually four ways of comparing for equality. Some subtle differences exist between the different methods:
The referenceequals() Method
ReferenceEquals() is a static method that tests whether two references refer to the same instance of a class, specifically whether the two references contain the same address in memory.
ReferenceEquals() will always return true if supplied with two references that refer to the same object instance, and false otherwise. It does, however, consider null to be equal to null:
SomeClass x, y;
x = new SomeClass();
y = new SomeClass();
bool B1 = ReferenceEquals(null, null); // returns true
bool B2 = ReferenceEquals(null,x); // returns false
bool B3 = ReferenceEquals(x, y); // returns false because x and y
// point to different objects
The virtual equals() Method
The System.Object implementation of the virtual version of Equals() also works by comparing references. However, because this method is virtual, we can override it in our own classes to compare objects by value. In particular, if we intend instances of our class to be used as keys in a dictionary, we will need to override this method to compare values.
The static equals() Method
The static version of Equals() actually does the same thing as the virtual instance version. The difference
is that the static version takes two parameters and compares them for equality.
Comparison operator (==). The comparison operator an intermediate option between strict value comparison and strict reference comparison. In most cases, writing the following means that we are comparing references: bool b = (x == y); // x, y object references
Дата добавления: 2015-09-18 | Просмотры: 709 | Нарушение авторских прав
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 |
|