[英]Unreachable code when overriding Object.Equals and implementing IEquatable<>?
I'm a litte bit confused right now. 我现在有点困惑。 From my understanding the .NET runtime will pick the overloaded method that best suits the given parameter's type.
根据我的理解,.NET运行时将选择最适合给定参数类型的重载方法。 So I would think, that in the snippet below the method
Equals(object obj)
will never be called with an instance of type Entry
. 所以我认为,在方法
Equals(object obj)
下面的代码段中,永远不会使用Entry
类型的实例来调用它。 Instead - because there exists the method Equals(Entry other)
that has the correct parameter type - it will be called. 相反-因为存在方法
Equals(Entry other)
具有正确的参数类型-它将被调用。
The documentation for IEquatable
on MSDN states that MSDN上的
IEquatable
文档指出:
If you implement IEquatable, you should also override the base class implementations of Object.Equals(Object) and GetHashCode so that their behavior is consistent with that of the IEquatable.Equals method.
如果实现IEquatable,则还应该重写Object.Equals(Object)和GetHashCode的基类实现,以使它们的行为与IEquatable.Equals方法的行为一致。 If you do override Object.Equals(Object), your overridden implementation is also called in calls to the static Equals(System.Object, System.Object) method on your class.
如果您确实重写Object.Equals(Object),则在对类上的静态Equals(System.Object,System.Object)方法的调用中也会调用重写的实现。
My questions are: 我的问题是:
Equals(object obj)
method below will never be called with an instance of type Entry
? Entry
类型的实例调用下面的Equals(object obj)
方法吗? return false
in the Equals(object obj)
method below? Equals(object obj)
方法中return false
是否就足够了? The code I refer to: 我引用的代码:
sealed class Entry : IEquatable<Entry> {
...
// Overrides Object.Equals
public override bool Equals(object obj)
{
if (obj is Entry)
{
return this.Equals(obj as Entry); // Is this code reachable?
}
return false;
}
// Implements IEquatable<Entry>.Equals
public bool Equals(Entry other)
{
return this.Hash.Equals(other.Hash)
&& this.Path.Equals(other.Path)
&& this.Order.Equals(other.Order);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
Thanks in advance for helping me! 在此先感谢您的帮助!
Is it correct, that the Equals(object obj) method below will never be called with an instance of type Entry?
是正确的,永远不会使用Entry类型的实例调用下面的Equals(object obj)方法吗?
No. Consider: 不,请考虑:
object entry1 = new Entry(...);
object entry2 = new Entry(...);
bool equal = entry1.Equals(entry2);
The compile-time type of entry2
is object
, not Entry
, so this will still call Equals(object)
. entry2
的编译时类型是object
,而不是Entry
,因此仍将调用Equals(object)
。
(Note that your GetHashCode
implementation is decidedly dodgy, by the way - and you're currently not guarding against nulls anywhere. It doesn't help that we don't know whether Entry
is a class or a struct.) (顺便说一下,请注意,您的
GetHashCode
实现绝对是狡猾的,并且您目前无法在任何地方防止null。我们不知道Entry
是类还是结构也无济于事。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.