为了更好的述说剩下两个函数,先解释一下等价的意义。对于等价的意义,就是自反、对称以及传递。
所谓自反,即a == a;
而对称,是a == b,则b == a;
传递是 a == b,b == c,则 a == c;
理解等价的意义后,那么在实现类型的判等函数也要满足这个等价规则。
对于可以重载的两个判等函数,首先来介绍的是类型的Equals函数,其大致形式如下:
public override bool Equals( object right );
那么对于一个类型的Equals要做些什么操作呢,一般来说大致如下:
public class KeyData
{
private int nData;
public int Data
{
get{ return nData; }
set{ nData = value; }
}
public override bool Equals( object right )
{
//Check null
if( right == null )
return false;
//check reference equality
if( object.ReferenceEquals( this, right ) )
return true;
//check type
if( this.GetType() != right.GetType() )
return false;
//convert to current type
KeyData rightASKeyData = right as KeyData;
//check members value
return this.Data == rightASKeyData.Data;
}
}
如上增加了一个类型检查,即
if( this.GetType() != right.GetType() )
这部分,这是由于子类对象可以通过as转化成基类对象,从而造成不同类型对象可以进行判等操作,违反了等价关系。