重写GetHash code重写、GetHash、code

2023-09-10 23:32:22 作者:酒酿樱桃子

如你所知,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.