本文介绍了IEquatable中的T实施是参考检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个实现 IEquatable< T>
的类.是否有必要在 Equals()
中进行引用检查?还是在框架中进行了检查?
I have a class that imlements IEquatable<T>
. Is it necessary to do a refrence check in Equals()
or is it taken care of in the framework?
class Foo : IEquatable<Foo>
{
int value;
Bar system;
bool Equals(Foo other)
{
return this == other ||
( value == other.value && system.Equals(other.system) );
}
}
在上面的示例中, this == other
语句是多余的还是必要的?
In the above example is the this==other
statement superfluous or necessary?
我了解我需要按照以下说明更正代码:
I understand I need to correct the code as follows:
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);
}
感谢您的答复.
推荐答案
我认为这是必要的.参考检查是比较对象时可以执行的第一步,也是第一步.
I believe that it's necessary. The reference check is the first, quick step you can perform when comparing objects.
在您给出的示例中,请确保在访问 other 的值之前,先检查其是否为null.
In the example you have given, be sure to check that other is not null before accessing its values.
bool Equals(Foo other)
{
if(other == null) return false;
if(this == other) return true;
// Custom comparison logic here.
}
这篇关于IEquatable中的T实施是参考检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!