
<
Item 9: Equality
public static bool ReferenceEquals(object left, object right);- Never redefine
- Return true: same reference identity
- Specially, return false when compare two value type variable(due to boxing)
public static bool Equals(object left, object right);- Never redefine
- Call
ReferenceEqualsand instanceEquals()to comapre two object instances
-
public virtual bool Equals(object right);- Equality
- reflexive: a == a
- symmetric: a == b <--> b == a
- transitive: a == b, b == c –> a == c
- Default
- Reference type: same with
Object.ReferenceEquals() - Value type: have been override by
System.ValueType, but we should create an override ofValueType.Equals()when we create a value type.
- Reference type: same with
- How to override
- Impliment
IEquatable<T> - Impliment
GetHashCode()- Equal objects must produce equal hash codes
- Hash code must be object invariants
- Must produce an even distribution to be efficient
- Standard pattern
public class Foo : IEquatable<Foo>
{
public override bool (object right)
{
// This reference is never null in C# methods
if (object.ReferenceEquals(right, null))
return false;
if (object.ReferenceEquals(this, right))
return true;
// To handle inheritance hierarchy problem
if (this.GetType() != right.GetType())
return false;
// Compare this type's contents here:
return this.Equals(right as Foo);
}
// IEquatable<Foo> Members
public bool (Foo other)
{
// Elided: this.x == other.x && this.y == other.y, etc.
return true;
}
}
- Impliment
- Equality
-
public static bool operator ==(MyClass left, MyClass right);- Redefine for value type, not reference type




近期评论