【问题标题】:nested List Compare Equals嵌套列表比较等于
【发布时间】:2013-05-05 22:07:10
【问题描述】:

我有这个 C# 类

 public class EntryClass
    {
        public string Field { get; set; }
        public List<FieldKeyValuePair<string, string>> FieldKeyValPairs { get; set; }

        public bool Equals(EntryClass other)
        {
            return Field.Equals(other.Field)
                && FieldKeyValPairs.Equals(other.FieldKeyValPairs);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != this.GetType()) return false;
            return Equals((EntryClass)obj);

        }
    }

    public class FieldKeyValuePair<K, V>
    {
        public K Key { get; set; }
        public V Value { get; set; }

        public bool Equals(FieldKeyValuePair<K, V> other)
        {
            return Key.Equals(other.Key)
                && Value.Equals(other.Value);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != this.GetType()) return false;
            return Equals((FieldKeyValuePair<K, V>)obj);
        }

    }

尝试做Assert.IsTrue(expected.SequenceEqual(actual)); 总是给我错误,我看到即使预期和实际具有相同的 FieldKeyValPairs 这个表达式总是命中错误&amp;&amp; FieldKeyValPairs.Equals(other.FieldKeyValPairs);

编辑 并且预期和实际的类型是

 List<EntryClass> expected = new List<EntryClass>(); // TODO: 
         List<EntryClass> actual = new List<EntryClass>();

【问题讨论】:

  • 他解释得很好,但它的格式问题。他提供的代码示例末尾描述了他的问题。
  • @IAbstract 更新了问题

标签: c# list c#-4.0 collections


【解决方案1】:

也许你只是忘了重写 GetHashCode()。一些比较算法首先比较哈希码以加快计算速度。

有关更多信息,请参阅此答案: Why is it important to override GetHashCode when Equals method is overridden?

【讨论】:

  • 我确实忘记了我添加了它们,但我仍然注意到当返回 Field.Equals(other.Field) && FieldKeyValPairs.Equals(other.FieldKeyValPairs);执行它没有达到此类 FieldKeyValPairs 的等于覆盖
  • @Justin 您应该添加更多单元测试来独立测试每个方法。也许您可以从直接测试 FieldKeyValuePair.Equals 函数开始,而不是通过列表比较来测试它们。
【解决方案2】:

我必须改变 返回 Field.Equals(other.Field) && FieldKeyValPairs.Equals(other.FieldKeyValPairs);

到

      return Field.Equals(other.Field)
            && FieldKeyValPairs.SequenceEqual(other.FieldKeyValPairs);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-03
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多