在C#接口实现中覆盖equals

Dav*_*ave 3 c# equals interface-implementation

我有一个实现接口的类,例如:

interface IInterface
{
   string PropA { get; }
   string PropB { get; }
}

class AClass : IInterface
{
   string PropA { get; protected set; }
   string PropB { get; protected set; }
}
Run Code Online (Sandbox Code Playgroud)

平等基于PropA和PropB确定.覆盖AClass的Equals方法时,我是否应该尝试将obj强制转换为AClass,如下所示:

public override bool Equals(object obj)
{
   AClass other = obj as AClass;
   return other != null 
       && AClass.PropA == other.PropA 
       && AClass.PropB == PropB;
}
Run Code Online (Sandbox Code Playgroud)

或者我应该尝试将obj强制转换为IInterface,如下所示:

public override bool Equals(object obj)
{
   IInterface other = obj as IInterface;
   return other != null 
       && AClass.PropA == other.PropA 
       && AClass.PropB == PropB;
}
Run Code Online (Sandbox Code Playgroud)

Ser*_*rvy 6

可以做任何你想做的事.这两者在功能上是不一样的,但对你来说这是"正确的"是我们无法回答的.如果我有一个BClass实现相同接口类,它具有相同的值这两个属性,应该就等于你的AClass目标?如果是,做后者,如果没有,做前者.

就个人而言,我会发现后者有关.一般来说,我发现如果一个类要实现自己的个人等式定义,其他类不应该等于它.一个主要原因是,如果平等是对称的,那是更可取的.也就是说aclass.Equals(bclass)应该返回同样的东西bclass.Equals(aclass).当您不将相等性限制为相同类型时获得该行为是很难的.它需要所有相关课程的合作.

如果你有一些令人信服的理由来比较IInterface它们可能是不同的底层类但仍然是"相等"的实现,我个人更喜欢创建一个IEqualityComparer<IInterface>定义该接口的相等性.这将与两个实现类中的任何一个的相等定义分开.