首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >IEquatable<>的替代方案

IEquatable<>的替代方案
EN

Stack Overflow用户
提问于 2022-05-05 16:22:29
回答 1查看 76关注 0票数 0

假设我们有一个包含其他复杂类型的复杂结构,甚至可能包含它自己。

代码语言:javascript
复制
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()方法的技术部分。我们的结构越大,覆盖的方法就越多。

它看起来糟透了,并且要求对所有内部类型都做同样的事情。

代码语言:javascript
复制
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种类型,还有一些嵌套类型等呢?

使用类似于混合组合设计模式的方法实现起来似乎更加复杂。

EN

回答 1

Stack Overflow用户

发布于 2022-05-30 12:44:40

首先,IEquatable<T>对引用类型的性能没有影响。我会放弃您所有的Equals()逻辑,并完成它。除非您真的这么做了,否则不希望通过引用获得相等。

然后,唯一合理的解决方案是为对象的标识引入一个Guid

代码语言:javascript
复制
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();
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72130541

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档