C# GetHashCode() High Performance Hashing Algorithm
Possible Duplicate:
What is the best algorithm for an overridden System.Object.GetHashCode?
This is known to us that if we override the Equals
method of Object
in our custom types, we should also override and provide an implementation of GetHashCode
method to support generating unique hash codes for use in support of Hashtable
and Dictionary
collection classes and may be other classes.
This mandates our implementation of the hashing algorithm used inside our overriden
GetHashCode
method is optimal and accurate ie it generates a unique hash of the type and also does that as quickly as possible to improve performance of application that uses our type.
My question is to which hashing algorithms are accurate and give optimal performance when used in GetHashCode
implementation? Or, should we only use the base type's GetHashCode
implementation? I would like to know this answer for both value types
and reference types
..
Edit: Here's an example of a class below on why I would need to override Equals
:
public class Laptop : LaptopBase
{
public readonly string Make;
public readonly string ProcessorArch;
public readonly int MemorySupported;
public readonly int HardDiskGBSupported;
public readonly Color ColorName;
public Laptop(make, procArch, memorySupp, hdGB, color)
{
Make = make;
ProcessorArch = procArch;
MemorySupported = memorySupp;
HardDiskGBSupported = hdGB;
ColorName = color;
}
}
Now, I want to return true for 2 Laptop instances that have all the above defined fields matching with each other so that requires to override the Equals
and GetHashCode
method and also another requirement as you can see is that this is a derived class and may be re-used further and support a number of methods; and thus, cannot be made a value type (struct). I tried with 2 instances of above type with all matching instance fields and if I use the base implementation of Equals
- it returns false
where I want it to be true
.. How would I support such a scenario?
It depends on the type it is implemented on, but it should give good dispersion of values and it is NOT a must for GetHashCode() to return a unique values. It should base on those fields that are used in your Equals implementation and those fields should be immutable. So requirements for Equals/GetHashCode are the same for structs and classes.
And as Henk said, it is better to not override Equals/GetHashCode at all...
链接地址: http://www.djcxy.com/p/39762.html