c# - Comment mieux mettre en œuvre les Égalités pour les types personnalisés

Mots clés : c#.netclassc#

meilleur 3 Réponses c# - Comment mieux mettre en œuvre les Égalités pour les types personnalisés

vote vote

96

public override bool Equals ( object obj ) {    return Equals(obj as Point2); }  public bool Equals ( Point2 obj ) {    return obj != null && obj.X == this.X && obj.Y == this.Y ...     // Or whatever you think qualifies as the objects being equal. } 
vote vote

88

using System; namespace MyNameSpace {     public class DomainEntity     {         public virtual int Id { get; set; }          public override bool Equals(object other)         {             return Equals(other as DomainEntity);         }          public virtual bool Equals(DomainEntity other)         {             if (other == null) { return false; }             if (object.ReferenceEquals(this, other)) { return true; }             return this.Id == other.Id;         }          public override int GetHashCode()         {             return this.Id;         }          public static bool operator ==(DomainEntity item1, DomainEntity item2)         {             if (object.ReferenceEquals(item1, item2)) { return true; }             if ((object)item1 == null || (object)item2 == null) { return false; }             return item1.Id == item2.Id;         }          public static bool operator !=(DomainEntity item1, DomainEntity item2)         {             return !(item1 == item2);         }     } } 
vote vote

77

// using strongly-typed overload of Equals public override bool Equals(object obj) => (obj is Point2 other) && Equals(other);  public bool Equals(Point2 other); 
// using the == operator (requires != to also be defined) public override bool Equals(object obj) => (obj is Point2 other) && this == other;  public static bool operator ==(Point2 lhs, Point2 rhs); public static bool operator !=(Point2 lhs, Point2 rhs); 

Questions similaires