我有一个实现 IEquatable<T>
的类.是否有必要在 Equals()
中进行引用检查还是在框架中处理?
class Foo : IEquatable<Foo>
{
int value;
Bar system;
bool Equals(Foo other)
{
return this == other ||
( value == other.value && system.Equals(other.system) );
}
}
在上面的例子中是this==other
声明是多余的还是必要的?
更新1
我知道我需要按如下方式更正代码:
bool Equals(Foo other)
{
if( other==null ) { return false; }
if( object.ReferenceEquals(this, other) ) { return true; } //avoid recursion
return value == other.value && system.Equals(other.system);
}
感谢您的回复。
最佳答案
这通常是一种优化 - 这将是一个奇怪的 Equals
实现,没有它就会失败。因此,我不认为它是必要的——但它也没有“在框架中得到处理”。 I 是实现成本低廉的优化,因此通常值得包括在内。
请注意,如果您还重载==
,那么您可能应该使用object.ReferenceEquals
来执行这些比较。
关于c# - 在 IEquatable<T> 实现中需要进行引用检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4682388/