重写GetHash code [英] Overriding GetHashCode

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

问题描述

如你所知,GetHash code返回一个半唯一值,可以用来识别一个集合对象实例。作为一个很好的做法,建议重写此方法并实现自己的。

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.

推荐答案

如果您覆盖GetHash code(),您还需要重写的equals(),operator ==和operator!​​=。而且必须非常小心,以满足所有这些方法的要求。

If 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 non-immutable types.

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

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