将带有接口的EqualityComparer作为通用参数调用是否有意义

问题描述 投票:0回答:1

假设我有一个代码:

public interface IInterface
{
    //  Properties...
}

internal class Realisation : IInterface, IEquatable<IInterface>
{
    //  Properties...

    public bool Equals(IInterface other)
    {
        //  ...
    }

    public override bool Equals(object obj)
    {
        return Equals(obj as IInterface);
    }

    public override int GetHashCode()
    {
        //  ...
    }
}

目的是不具有重复/不同版本的相等代码。

我无权访问Realisation,因为代码在库中。如果我必须调用IInterface的相等比较器,那么在这里调用EqualityComparer<IInterface>.Default是否有意义?它会使用Equals(IInterface other)实现吗?或者平等实施是否应该在课堂之外?我应该提供自定义IEqualityComparer<IInterface>吗?

编辑

  • 添加了Equals(object obj)GetHashCode()覆盖
c# interface iequalitycomparer
1个回答
0
投票

我建议你把你的比较器放在你的课外,因为它满足Single responsibility principle - 类只做一个任务比多个事情(它不应该成为超级clas)和(Open Close Principle)Extend your class rather than modifying your class,这意味着保持代码在seprate class rahter然后在你的类。 (这是我的建议)


如果您可以访问类代码而不是使用IEquatable,那么还有一件事是覆盖基础对象类方法,如Equals & GetHashcode

© www.soinside.com 2019 - 2024. All rights reserved.