GetHashCode问……
public struct ErrorMessage
{
private string strMsg;
private int nErrorCode;
private DateTime dtInvoked;
public ErrorMessage( string Msg, int ErrorCode )
{
strMsg = Msg;
nErrorCode = ErrorCode;
dtInvoked = DateTime.Now;
}
public bool TestHashCode()
{
return this.GetHashCode() == strMsg.GetHashCode();
}
}
// Test "GetHashCode" function in value type
ErrorMessage err = new ErrorMessage( "Test", 0 );
if( err.TestHashCode() )
Debug.WriteLine( "Both hash code equal!" );
else
Debug.WriteLine( "Not equal!" );
按《Effective C#》所说,应该是会输出Both hash code equal!,但我经过测试发现是Not equal!谁能解释一下,我是用.NET 2.0测试的,我在想会不会是版本的问题,2.0做了更新?(上面omit了部分代码)
问题点数:30、回复次数:2Top
1 楼yeerh(边城浪)回复于 2006-10-01 20:51:45 得分 1
this.GetHashCode()实际上执行的是其默认基类 object 的GetHashCode()
而strMsg.GetHashCode(); 实际的是String类的GetHashCode()...
在由于在String类中重写了基类的GetHashCode();
所以比较结果时肯定是不等的..Top
2 楼Knight94(愚翁)回复于 2006-10-06 15:59:05 得分 29
to 我是用.NET 2.0测试的,我在想会不会是版本的问题,2.0做了更新?
是的,看来对于2.0来说,对于struct的GetHashCode不单单是从第一个元素作为HashCode基础。Top




