简体   繁体   中英

If I override ToString, do i need to override Equals and GetHashCode as well?

I am sure if I override Equals, I need to override GetHashCode as well to make sure Dictionary etc.. data structures works as expected.

But if i just want to override ToString, do I still have to override Equals and GetHashCode methods.

Overriding those three methods serve three different purposes:

  1. ToString: Output representation of the object.
  2. Equals: If two objects represent the same thing. Uses GetHashCode in it's default implementation.
  3. GetHashCode: Used for indexing of objects. Several advanced topics here including semi-uniqueness and distribution of hashvalues.

As you can see 2 and 3 are related, but 1 is separate. Unless you implement Equals to simply test if the ToString of two objects are equals, which would most likely be a mistake. :)

So the short answer has allready been given: You can override ToString without overriding the two other methods. It is quite normal to even overload the ToString method. See DateTime for an example: http://msdn.microsoft.com/en-us/library/zdtaw1bw.aspx

不,您不必重写EqualsGetHashCode ,它们与ToString无关

如果只重写ToString(),你不需要重写Equals和GetHashCode

You can override it just for a certain class, or do you mean override it on every class / object?

public class YourClass
{
    // Other stuff here...

    public override string ToString()
    {
        // Do whatever you want here instead, or return base.ToString(); for the default behavior
    }
}

But no, its not related to other methods and you can pick and choose what you want to override

ToString is only meant to be a string representation of your object. Nothing more.

As you have stated though, were you to override Equals, it is best practice to override GetHashCode for HashTables. However the two operations are unrelated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM