为什么我的直接 Equals 调用通过,但在嵌套时失败?

Why does my direct Equals call pass, but fails when nested?

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

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;
    }
}

而这个 "parent" 结构,其中一个成员是 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 覆盖中遗漏了一些东西来解释数组? childEquals方法没有枚举到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 child2 = new ChildStruct{Valid = true, Value1 = 1};

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

    // fails during checking for equality of children array!
    Assert.AreEqual(parent1, parent2);
}

为了 ParentStruct 相等,您需要确定是什么使两个 ChildStruct 数组相等,并相应地更改 ParentStruct 的 equals 方法的最后一行。例如,如果它们仅在包含相同顺序 的等效子项 时才应该是 "equal",则这样可以工作:

return Id == other.Id && children.SequenceEqual(other.children);