c# - When implementing IEqualityComparer.GetHashCode(T obj), can I use the current instance's state, or do I have to use obj? -
How do I implement IEqualityComparer, has a parameter for GetHashCode (T obj)? This is definitely not a stable object, so why can not I just use the current example to generate the hash code? I am curious because I am trying to do this:
Public Abstract Class BaseClass: IEqualityComparer & LT; BaseClass & gt; {Public abstract int GetHashCode (BaseClass obj); } Public Category DerivedClass: Base Class {public int MyData; Public override int gatehashcode (baseclus obje) {MyData.GetHashCode (); // or I have to do this: // Return (DerivedClass) obj.MyData.GetHashCode (); }} I am trying to stop the artists because it is actually being used in high-performance code.
I think the main issue here is that you are confusing with
IEquatable & Lt; T & gt; A method for determining that defines the current example ( this ) is equivalent to an example of the same type. In other words it is tested for objA.Equals (objB) . When applying this interface, it is recommended that you also get GetHashCode () example method IEqualityComparer & lt override;. T & gt; defines ways to define that given two objects of the given type are equal, in other words, it is for testing comparer.Equals (objA, objB) . Therefore, the need to provide an object as a parameter for GetHashCode (which is different from GetHashCode , which it gets from the object Is] You can think of iequatable & lt; T & gt; as a way to tell your object, " How do I know this If I'm equal to something else, "and IEqualityComparer as a way to tell your object," How do I know that Other things Is similar ". For some good examples of how these two interfaces are used in the framework:
- The tool
iequatable - IEqualityComparer & lt; t & gt; the code to set the hash? In the state all is variable, you can click anywhere no anywhere Is used (example For
HashSet & lt; T & gt; or dictionary & lt; T, V & gt; ) The hash code will be cached and will be used for efficient lookup. If this hash code can be changed because the comparison situation changes, which will completely destroy the usefulness of the stored data structure of hash. Now, if the state is not unstable (i.e. it is only set and can not be modified throughout the lifetime of the comparator), then yeah, you can, but I will still suggest against it, as long as you have Not good reason Finally, you mentioned performance honestly, it seems like this I suggest that unless you can not make sure that a special line of code is causing the problem As long as you do not worry too much about performance.
Comments
Post a Comment