假设我们有一个包含其他复杂类型的复杂结构,甚至可能包含它自己。
public class Box {
public string Name { get; set; }
public List<Box> Boxes { get; set; }
public List<Item> Items { get; set; }
public SomeOtherComplexType BlaBla { get; set; }
...
}我们需要一种比较这些复杂类型的可能性。
因为当涉及泛型类型时,重写object.Equals()的性能会很差,所以我看到了很多IEquatable<>的用法。
问题是,使用IEquatable<>会极大地使代码变得丑陋,这就混合了业务逻辑和重写Equeals()和GetHashCode()方法的技术部分。我们的结构越大,覆盖的方法就越多。
它看起来糟透了,并且要求对所有内部类型都做同样的事情。
public class Box : IEquatable<Box> {
public string Name { get; set; }
public List<Box> Boxes { get; set; }
public List<Item> Items { get; set; }
public SomeOtherComplexType BlaBla { get; set; }
public bool Equals(Box other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return
(
Name == other.Name||
Name != null &&
Name.Equals(other.Name)
) &&
(
Boxes == other.Boxes ||
Boxes != null &&
Boxes.SequenceEqual(other.Boxes)
) &&
(
Items == other.Items ||
Items != null &&
Items.SequenceEqual(other.Items)
) &&
(
BlaBla == other.BlaBla ||
BlaBla != null &&
BlaBla.SequenceEqual(other.BlaBla)
);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = 14;
if (Name != null)
hashCode = hashCode * 14 + Name.GetHashCode();
if (Boxes != null)
hashCode = hashCode * 14 + Boxes.GetHashCode();
if (Items != null)
hashCode = hashCode * 14 + Items.GetHashCode();
if (BlaBla!= null)
hashCode = hashCode * 14 + BlaBla.GetHashCode();
return hashCode;
}
}
}有什么办法可以让事情变得更糟吗?或者其他的选择。
也许有一些方法可以隐藏这个实现,并使其尽可能自动化?只有4个字段,但是如果我们有一些复杂的类型,其中有~30种类型,还有一些嵌套类型等呢?
使用类似于混合组合设计模式的方法实现起来似乎更加复杂。
发布于 2022-05-30 12:44:40
首先,IEquatable<T>对引用类型的性能没有影响。我会放弃您所有的Equals()逻辑,并完成它。除非您真的这么做了,否则不希望通过引用获得相等。
然后,唯一合理的解决方案是为对象的标识引入一个Guid:
public class Box : IEquatable<Box>
{
public Box(Guid id)
{
Id = id;
}
public Guid Id { get; }
public override bool Equals(object obj) => obj is Box box && Equals(box);
public bool Equals(Box other) => Id == other.Id;
public override int GetHashCode() => Id.GetHashCode();
}https://stackoverflow.com/questions/72130541
复制相似问题