为什么我的直接Equals呼叫通过但嵌套时失败?

我正在尝试为我的代码中的某些结构实现Equals覆盖。我有以下“子”结构

public struct ChildStruct
{
    public bool Valid;
    public int Value1;

    public override bool Equals(object obj)
    {
         if (obj == null || GetType() != obj.GetType()) 
         {
             return false;
         }

         ChildStruct other = (ChildStruct) obj;

         return Valid == other.Valid && Surface == other.Value1;
    }
}

这个“父”结构,其中一个成员是ChildStructs的数组

public struct ParentStruct
{
    public int Id;
    public ChildStruct[] children;

    public override bool Equals(object obj)
    {
         if (obj == null || GetType() != obj.GetType()) 
         {
             return false;
         }

         ParentStruct other = (ParentStruct) obj;

         // am I comparing ChildStructs array correctly?
         return Id == other.Id && children == other.children;
    }
}

在我的覆盖Equals方法的Nunit测试中,直接比较类型为ChildStruct的对象通过,但是对ParentStructs的单元测试失败。我是否在ParentStruct的Equals覆盖中缺少某些内容来说明数组?子Equals方法不是枚举到children数组中的所有元素吗?

单位代码:

[Test]
public void ChildEqual()
{ 
    var child1 = new ChildStruct{Valid = true,Value1 = 1};
    var child2 = new ChildStruct{Valid = true,Value1 = 1};

    // passes!
    Assert.AreEqual(child1,child2);
}

[Test]
public void ParentEqual()
{ 
    var child1 = new ChildStruct{Valid = true,Value1 = 1};

    var parent1 = new ParentStruct{Id = 1,children = new[] {child1,child2}}
    var parent2 = new ParentStruct{Id = 1,child2}}

    // fails during checking for equality of children array!
    Assert.AreEqual(parent1,parent2);
}
liqilong2259 回答:为什么我的直接Equals呼叫通过但嵌套时失败?

您需要确定是什么使得ChildStruct的两个数组相等,以实现ParentStruct相等,并相应地更改ParentStruct的equals方法的最后一行。例如,如果只包含相同顺序的相等子元素 ,则假定它们是“相等的”,这将起作用:

return Id == other.Id && children.SequenceEqual(other.children);
本文链接:https://www.f2er.com/3107607.html

大家都在问