我正在寻找以IEquatable<T>
隐式类型检查的方式实现的最佳方法。如果我调用Equals
一个子类,我想确保我要比较的类型是相同的。请参阅下面的精简示例。
如果两个Child1
对象的 ID 相同,则应将其视为相等。在此示例中,如果它们的 ID 相同,则调用child1.Equals(child2)
将返回 true,这不是预期的行为。我基本上想强制实例使用需要参数Child1
的重载,而不仅仅是从与.Equals
Child1
Child1
我开始认为我以错误的方式处理这个问题。也许我应该把实现留Equals
在基类中,并确保this.GetType() == other.GetType()
?
public abstract class BaseClass : IEquatable<BaseClass>
{
public int ID { get; set; }
public bool Equals(BaseClass other)
{
return
other != null &&
other.ID == this.ID;
}
}
public sealed class Child1 : BaseClass
{
string Child1Prop { get; set; }
public bool Equals(Child1 other)
{
return base.Equals(other as BaseClass);
}
}
public sealed class Child2 : BaseClass
{
string Child2Prop { get; set; }
public bool Equals(Child2 other)
{
return base.Equals(other as BaseClass);
}
}