[英]Why is ReferenceEquals still used with value types?
There is a nice explanation why object.ReferenceEquals(this, obj)
must not be used for value types:有一个很好的解释为什么
object.ReferenceEquals(this, obj)
不能用于值类型:
When comparing values using ReferenceEquals, if objA and objB are value types, they are boxed before they are passed to the ReferenceEquals method.
使用 ReferenceEquals 比较值时,如果 objA 和 objB 是值类型,则在将它们传递给 ReferenceEquals 方法之前将它们装箱。 This means that even if both objA and objB represent the same instance of a value type, the ReferenceEquals method nevertheless returns false
这意味着即使 objA 和 objB 都表示值类型的同一实例,ReferenceEquals 方法仍然返回 false
However, I found code similar to the following snippet:但是,我发现类似于以下代码段的代码:
internal readonly struct Foo
{
public override bool Equals(object obj)
{
if (object.ReferenceEquals(this, obj))
{
return true;
}
if (obj is Foo other)
{
return this.Equals(other);
}
return false;
}
public bool Equals(Foo other)
{
// ..
return true;
}
}
Is this just wrong or is there an edge case in which ReferenceEquals
could be useful (ie, evaluate to true) for value types, especially structs?这是错误的还是存在
ReferenceEquals
可能对值类型(尤其是结构)有用(即评估为真)的边缘情况?
It shouldn't be.不应该。 The code as-written is simply bad, in that it unnecessarily boxes something for a test that will never work.
编写的代码很糟糕,因为它不必要地为永远无法工作的测试打包了一些东西。 For completeness, a more useful and idiomatic pattern in this case would be:
为了完整起见,在这种情况下,更有用和惯用的模式是:
// custom Foo equality implementation
public bool Equals(Foo other)
{
// ...
}
// default object implemenentation
public override int GetHashCode() {...} // must match Equals(Foo) logic
public override bool Equals(object obj) => obj is Foo other && Equals(other);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.