why not just using GetHashCode in Equality?
This question already has an answer here:
Two unequal objects are not guaranteed to have unequal hashcodes (that's called a collision).This is what MSDN says:
If two objects compare as equal, the GetHashCode method for each object must return the same value. However, if two objects do not compare as equal, the GetHashCode methods for the two object do not have to return different values.
It's because there are more possibilities than there is hashcodes.
For example, let's take your class.
Already you have a problem, as the age range is the same range as the int
. That could be eliminated, of course: just use a byte
instead. Still, we've got a problem: strings. A .NET string is Unicode (UTF-16), so it has 65,536 possible characters for each letter. After that, it escalates quickly... a two character string can have up to 65,536 ^ 2 characters, ie 4,294,967,296 ( uint.MaxValue
) possibilities. That's a whole lot, and that's only two characters.
td;lr : you can't guarantee that two objects that are not equal will not have the same hashcode. At all. (unless it's a byte
or a short
or a sbyte
or a ushort
, but that's a technicality)
如果你想要一个很好的例子,试着看一下Resharper的一面。
public class Person : IEquatable<Person>
{
public string Name { get; set; }
public int Age { get; set; }
public bool Equals(Person other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return string.Equals(Name, other.Name) && Age == other.Age;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Person) obj);
}
public override int GetHashCode()
{
unchecked
{
return ((Name != null ? Name.GetHashCode() : 0) * 397) ^ Age;
}
}
}
链接地址: http://www.djcxy.com/p/39788.html