Comparing two instances of a class

后端 未结 8 783
礼貌的吻别
礼貌的吻别 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:12

    One way of doing it is to implement IEquatable

    public class TestData : IEquatable
    {
       public string Name {get;set;}
       public string type {get;set;}
    
       public List Members = new List();
    
       public void AddMembers(string[] members)
       {
          Members.AddRange(members);
       }
    
       public bool Equals(TestData other)
       {
            if (this.Name != other.Name) return false;
            if (this.type != other.type) return false;
    
            // TODO: Compare Members and return false if not the same
    
            return true;
       }
    }
    
    
    if (testData1.Equals(testData2))
        // classes are the same
    

    You can also just override the Equals(object) method (from System.Object), if you do this you should also override GetHashCode see here

提交回复
热议问题