我已经阅读了大量正确实施Equals()
和GetHashCode()
的文章。我有一些有很多成员变量的类,为此我必须实现一个Equals()
方法。到现在为止还挺好。但是,当实施GetHashCode()
时,我总是发现一个好的实现。据我所知,某些类别他们永远不会用在字典或散列表中,我不想花时间编写一个好的GetHashCode()
实现,所以我想出了以下虚拟“默认”实现:如果不需要GetHashCode()虚拟实现
public override int GetHashCode()
{
Debug.Fail("If you see this message, implement GetHashCode() properly");
// Always return the same value for all instances of this class. This ensures
// that two instances which are equal (in terms of their Equals() method)
// have the same hash code.
return 0;
}
我想问你的意见,如果这是一个可行的方法。
一方面,我不想花时间在执行GetHashCode()
时,我不必。另一方面,我希望我的代码干净有效。上述实现确保具有相同Equals()
结果的两个实例也具有相同的哈希码。当然,如果它真的会被用作字典中的关键字,那么性能会很糟糕。但是对于这种情况你会得到调试断言。
上述方法有什么缺点,我可能错过了?
看看这个SO问题。我不会说这是重复的,但它是绝对相关的:http://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode – Konamiman 2014-09-03 14:39:28
个人意见:调试和发布版本之间的显着差异(如崩溃与样本成功)是不好的主意。 – 2014-09-03 14:39:31
@AlexeiLevenkov这段代码在调试和发布之间无显着差异。如果'Debug.Fail'被执行并且被忽略,则没有区别。另请参阅我对Jon Skeet的答案的评论。 – Tobias 2014-09-03 15:41:40