Comparing two instances of a class

后端 未结 8 732
礼貌的吻别
礼貌的吻别 2020-12-03 17:33

I have a class like this

public class TestData
{
   public string Name {get;set;}
   public string type {get;set;}

   public List Members = ne         


        
相关标签:
8条回答
  • 2020-12-03 18:18

    You should implement the IEquatable<T> interface on your class, which will allow you to define your equality-logic. Actually, you should override the Equals method as well.

    public class TestData : IEquatable<TestData>
    {
       public string Name {get;set;}
       public string type {get;set;}
    
       public List<string> Members = new List<string>();
    
       public void AddMembers(string[] members)
       {
          Members.AddRange(members);
       }   
    
      // Overriding Equals member method, which will call the IEquatable implementation
      // if appropriate.
    
       public override bool Equals( Object obj )
       {
           var other = obj as TestData;
           if( other == null ) return false;
    
           return Equals (other);             
       }
    
       public override int GetHashCode()
       {
          // Provide own implementation
       }
    
    
       // This is the method that must be implemented to conform to the 
       // IEquatable contract
    
       public bool Equals( TestData other )
       {
           if( other == null )
           {
                return false;
           }
    
           if( ReferenceEquals (this, other) )
           {
                return true;
           }
    
           // You can also use a specific StringComparer instead of EqualityComparer<string>
           // Check out the specific implementations (StringComparer.CurrentCulture, e.a.).
           if( EqualityComparer<string>.Default.Compare (Name, other.Name) == false )
           {
               return false;
           }
           ...
    
           // To compare the members array, you could perhaps use the 
           // [SequenceEquals][2] method.  But, be aware that [] {"a", "b"} will not
           // be considerd equal as [] {"b", "a"}
    
           return true;
    
       }
    
    }
    
    0 讨论(0)
  • 2020-12-03 18:23

    First of all equality is difficult to define and only you can define as to what equality means for you

    1. Does it means members have same value
    2. Or they are pointing to same location.

    Here is a discussion and an answer here

    What is "Best Practice" For Comparing Two Instances of a Reference Type?

    0 讨论(0)
提交回复
热议问题