Overriding GetHashCode

This question already has an answer here:

  • What is the best algorithm for an overridden System.Object.GetHashCode? 17 answers

  • 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.

    The guidelines are here on MSDN. Most important quote:

    It is not a good idea to override operator == in non-immutable types.


    If you use resharper it can generate the GetHashCode(), Equals and operator method bodies for you.

    Access this menu by pressing Alt+Insert.

    http://www.jetbrains.com/resharper/webhelp/Code_Generation__Equality_Members.html


    In my personal usage, I only override when overriding equals method too. Generally, I do this for objects I know that I might run a LINQ to Objects query on, or some other comparison operation.

    I usually return, if say a LINQ to SQL entity or DTO object, the primary key value. Whatever you return, if you don't store the value locally, it may produce an unexpected result.

    HTH.

    链接地址: http://www.djcxy.com/p/39750.html

    上一篇: 正确实现GetHashCode

    下一篇: 重写GetHashCode