我有这个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,这个表达总是会遇到假&& FieldKeyValPairs.Equals(other.FieldKeyValPairs);
修改 预期和实际属于
类型 List<EntryClass> expected = new List<EntryClass>(); // TODO:
List<EntryClass> actual = new List<EntryClass>();
答案 0 :(得分:2)
可能你忘了重写GetHashCode()。一些比较算法首先比较哈希码以加速计算。
有关详细信息,请参阅此答案: Why is it important to override GetHashCode when Equals method is overridden?
答案 1 :(得分:0)
我不得不改变 返回Field.Equals(other.Field) &安培;&安培; FieldKeyValPairs.Equals(other.FieldKeyValPairs);
要
return Field.Equals(other.Field)
&& FieldKeyValPairs.SequenceEqual(other.FieldKeyValPairs);