我有以下内容:
var a = new List<OrderRule> {
new OrderRule("name", OrderDirection.Ascending),
new OrderRule("age", OrderDirection.Descending)
};
var b = new List<OrderRule> {
new OrderRule("name", OrderDirection.Ascending),
new OrderRule("age", OrderDirection.Descending)
};
var r = a.Equals(b);
即使这两个列表中包含相等的项,变量r也是假的。OrderRule类实现了IEquality接口。请注意,当方向(Direction)和属性(Property)都相等时,两个OrderRules是相等的。
public enum OrderDirection { ASC, DESC }
public class OrderRule : IEquatable<OrderRule> {
public OrderDirection Direction { get; }
public String Property { get; }
public OrderRule(String property, OrderDirection direction) {
Direction = direction;
Property = property;
}
public Boolean Equals(OrderRule other) {
if (other == null)
return false;
return Property.Equals(other.Property) && Direction.Equals(other.Direction);
}
public override Boolean Equals(Object obj) {
if (ReferenceEquals(null, obj))
return false;
if (ReferenceEquals(this, obj))
return true;
if (obj.GetType() != GetType())
return false;
return Equals(obj as IncludeRule);
}
public override Int32 GetHashCode() {
return HashCode.Of(Property).And(Direction);
}
}
我错过了什么?
List<T>
没有覆盖重写Equals
方法,基本上就是这么简单。 - Jon SkeetList<T>
没有实现IEquality
,也没有重写Equals
和GetHashCode
方法,因此进行的是引用比较。您可能想尝试使用Enumerable.SequenceEqual
。 - juharr