Overriding GetHashCode [duplicate]

2020-02-08 09:59发布

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.

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?

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

6条回答
Emotional °昔
2楼-- · 2020-02-08 10:28

I would normally override hashcode and equality checking methods for data classes (i.e. classes where the value semantics makes sense). Have a look at this question for a common implementation. If you do override hashcode override equals. Using a GUID is a pretty terrible idea because you want two objects which are different instances but have the same value to have the same hashcode and for equals to return true.

查看更多
叼着烟拽天下
3楼-- · 2020-02-08 10:37

you only need to override GetHashCode if you are overriding Equals. The default GetHashCode is implemented by the runtime in a similar way you wanted to do it - every object has a hidden field assigned by the runtime.

How to override GetHashCode

Actually your IDE should do this for you - when you type "override GetHashCode" the IDE should generate this boilerplate code. Visual Studio does not do it but SharpDevelop does.

查看更多
对你真心纯属浪费
4楼-- · 2020-02-08 10:39

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

查看更多
够拽才男人
5楼-- · 2020-02-08 10:40

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.

查看更多
等我变得足够好
6楼-- · 2020-02-08 10:44

Generally I use the aggregated GetHashCode from the component properties of the class. E.g.

public class Test
{
  public string Text { get; set; }
  public int Age { get; set; }

  public override GetHashCode()
  {
    int result = 
      string.IsNullOrEmpty(Text) ? 0 : Text.GetHashCode()
      + Age.GetHashCode();

    return result;
  }
}
查看更多
Bombasti
7楼-- · 2020-02-08 10:48

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.

查看更多
登录 后发表回答