2014-09-24 77 views
1

所以,我有一个实体接口,要求他们公开他们的身份IEquatable <'1>在接口

public interface IEntity<TIdentity> { 
    public TIdentity Id { get; } 
} 

现在我需要能够比较两个实体,其彼此,但我不能依靠EqualsGetHashCode默认的实现,因为实体应由其身份,而不是整体的签名进行比较。由于实现IEntity<'1>的每个类都应该具有可比性,因此我想直接在实体接口上声明IEquatable<'1>

那么..不起作用。当我在IEntity<'1>声明IEquatable<'1>接口强制执行类来实现如下:

public bool Equals(IEntity<'1> other) 

代替

public bool Equals(TypeImplementingIEntity other) 

所以在调用Equals两个实体,运行时指回Equals(object obj)因为类型的IEquatable<'1>提供的方法参数与实际类型不匹配!做什么?

回答

2

它应该工作。 Equals(IEntity<TIdentity>)应该优先于Equals(object)

您应该重写Equals(object)反正:

public override bool Equals(object other) { 
    return Equals(other as IEntity<TIdentity>); 
} 
+0

根据[这](http://stackoverflow.com/questions/371328/why-is-it-important-to- override-gethashcode-when-equals-method-is-overridden),重写'GetHashCode()'也很重要。 – 2014-10-10 03:20:07

+0

是的,你应该,但这不是这个问题的原因,所以我没有提到它。 – 2014-10-10 08:05:18