我有一个实现的类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
声明是多余的还是必要的?
Update 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
如果没有它,实施就会失败。因此我会not认为这是必要的,但也没有“在框架内得到照顾”。 I 是一种成本低廉的优化,因此通常值得包含。
请注意,如果您是also超载==
,那么你可能应该使用object.ReferenceEquals
来执行这些比较。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)