覆盖 GetHashCode [英] Overriding GetHashCode

查看:17
本文介绍了覆盖 GetHashCode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如您所知,GetHashCode 返回一个半唯一值,可用于标识集合中的对象实例.作为一种很好的做法,建议覆盖此方法并实现您自己的方法.

As you know, GetHashCode returns a semi-unique value that can be used to identify an object instance in a collection. As a good practice, it is recommended to override this method and implement your own.

我的问题是 - 在处理自定义对象时您是否覆盖此方法?如果是这样,您使用什么算法来生成唯一 ID?

My question is - do you override this method when working on custom objects? If so, what algorithm do you use to generate the unique ID?

我正在考虑生成一个 GUID,然后从该标识符中获取整数数据.

I was thinking about generating a GUID and then getting integer data from that identificator.

推荐答案

当你重写 GetHashCode() 时你还需要重写 Equals(), operator==operator!= .并且要非常小心地满足这些方法的所有要求.

When you override GetHashCode() you also need to override Equals(), operator== and operator!= . And be very careful to meet all the requirements for those methods.

指南位于 MSDN 上.最重要的引述:

The guidelines are here on MSDN. Most important quote:

在可变类型中覆盖运算符 == 不是一个好主意.

It is not a good idea to override operator == in mutable types.

这篇关于覆盖 GetHashCode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆