在.NET 中,如果 null 的哈希代码始终为零,则

假设像 System.Collections.Generic.HashSet<>这样的集合接受 null作为集合成员,那么可以问 null的哈希代码应该是什么。看起来这个框架使用了 0:

// nullable struct type
int? i = null;
i.GetHashCode();  // gives 0
EqualityComparer<int?>.Default.GetHashCode(i);  // gives 0


// class type
CultureInfo c = null;
EqualityComparer<CultureInfo>.Default.GetHashCode(c);  // gives 0

对于可为空的枚举,这可能会有(一点)问题

enum Season
{
Spring,
Summer,
Autumn,
Winter,
}

那么 Nullable<Season>(也称为 Season?)只能取五个值,但其中两个值,即 nullSeason.Spring,具有相同的哈希代码。

人们很容易写出这样一篇“更好”的平等比较文章:

class NewNullEnumEqComp<T> : EqualityComparer<T?> where T : struct
{
public override bool Equals(T? x, T? y)
{
return Default.Equals(x, y);
}
public override int GetHashCode(T? x)
{
return x.HasValue ? Default.GetHashCode(x) : -1;
}
}

但是为什么 null的散列码应该是 0呢?

编辑/添加:

有些人似乎认为这是关于覆盖 Object.GetHashCode()。其实不是。(作者。NET 的确在 Nullable<>结构中覆盖了 GetHashCode(),尽管这与 相关。)无参数 GetHashCode()的用户编写实现永远不能处理我们寻找的散列码是 null的对象的情况。

这是关于实现抽象方法 EqualityComparer<T>.GetHashCode(T)或以其他方式实现接口方法 IEqualityComparer<T>.GetHashCode(T)。现在,在创建到 MSDN 的这些链接时,我看到它说,如果这些方法的唯一参数是 null,那么它们将抛出一个 ArgumentNullException。这肯定是 MSDN 上的一个错误吧?一个都没有。NET 自己的实现抛出异常。在这种情况下,抛出将有效地打破任何企图将 null添加到 HashSet<>。除非 HashSet<>在处理 null项目时做了一些特别的事情(我将不得不测试它)。

最新编辑/补充:

现在我尝试调试。使用 HashSet<>,我可以确认使用默认的相等比较器,值 Season.Springnull威尔在同一个桶中结束。这可以通过非常仔细地检查私有数组成员 m_bucketsm_slots来确定。注意,按照设计,索引总是被1抵消。

然而,我上面给出的代码并不能解决这个问题。事实证明,当值为 null时,HashSet<>甚至不会询问相等比较器。这是来自 HashSet<>的源代码:

    // Workaround Comparers that throw ArgumentNullException for GetHashCode(null).
private int InternalGetHashCode(T item) {
if (item == null) {
return 0;
}
return m_comparer.GetHashCode(item) & Lower31BitMask;
}

这意味着,至少对于 ABC0,甚至不可能改变 null的散列。相反,解决方案是更改所有其他值的散列,如下所示:

class NewerNullEnumEqComp<T> : EqualityComparer<T?> where T : struct
{
public override bool Equals(T? x, T? y)
{
return Default.Equals(x, y);
}
public override int GetHashCode(T? x)
{
return x.HasValue ? 1 + Default.GetHashCode(x) : /* not seen by HashSet: */ 0;
}
}
12924 次浏览

Good question.

I just tried to code this:

enum Season
{
Spring,
Summer,
Autumn,
Winter,
}

and execute this like this:

Season? v = null;
Console.WriteLine(v);

it returns null

if I do, instead normal

Season? v = Season.Spring;
Console.WriteLine((int)v);

it return 0, as expected, or simple Spring if we avoid casting to int.

So.. if you do the following:

Season? v = Season.Spring;
Season? vnull = null;
if(vnull == v) // never TRUE

EDIT

From MSDN

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

In other words: if two objects have same hash code that doesn't mean that they are equal, cause real equality is determined by Equals.

From MSDN again:

The GetHashCode method for an object must consistently return the same hash code as long as there is no modification to the object state that determines the return value of the object's Equals method. Note that this is true only for the current execution of an application, and that a different hash code can be returned if the application is run again.

So long as the hash code returned for nulls is consistent for the type, you should be fine. The only requirement for a hash code is that two objects that are considered equal share the same hash code.

Returning 0 or -1 for null, so long as you choose one and return it all the time, will work. Obviously, non-null hash codes should not return whatever value you use for null.

Similar questions:

GetHashCode on null fields?

What should GetHashCode return when object's identifier is null?

The "Remarks" of this MSDN entry goes into more detail around the hash code. Poignantly, the documentation does not provide any coverage or discussion of null values at all - not even in the community content.

To address your issue with the enum, either re-implement the hash code to return non-zero, add a default "unknown" enum entry equivalent to null, or simply don't use nullable enums.

Interesting find, by the way.

Another problem I see with this generally is that the hash code cannot represent a 4 byte or larger type that is nullable without at least one collision (more as the type size increases). For example, the hash code of an int is just the int, so it uses the full int range. What value in that range do you choose for null? Whatever one you pick will collide with the value's hash code itself.

Collisions in and of themselves are not necessarily a problem, but you need to know they are there. Hash codes are only used in some circumstances. As stated in the docs on MSDN, hash codes are not guaranteed to return different values for different objects so shouldn't be expected to.

It is 0 for the sake of simplicity. There is no such hard requirement. You only need to ensure the general requirements of hash coding.

For example, you need to make sure that if two objects are equal, their hashcodes must always be equal too. Therefore, different hashcodes must always represent different objects (but it's not necessarily true vice versa: two different objects may have the same hashcode, even though if this happens often then this is not a good quality hash function -- it doesn't have a good collision resistance).

Of course, I restricted my answer to requirements of mathematical nature. There are .NET-specific, technical conditions as well, which you can read here. 0 for a null value is not among them.

So this could be avoided by using an Unknown enum value (although it seems a bit weird for a Season to be unknown). So something like this would negate this issue:

public enum Season
{
Unknown = 0,
Spring,
Summer,
Autumn,
Winter
}


Season some_season = Season.Unknown;
int code = some_season.GetHashCode(); // 0
some_season = Season.Autumn;
code = some_season.GetHashCode(); // 3

Then you would have unique hash code values for each season.

It doesn't have to be zero -- you could make it 42 if you wanted to.

All that matters is consistency during the execution of the program.

It's just the most obvious representation, because null is often represented as a zero internally. Which means, while debugging, if you see a hash code of zero, it might prompt you to think, "Hmm.. was this a null reference issue?"

Note that if you use a number like 0xDEADBEEF, then someone could say you're using a magic number... and you kind of would be. (You could say zero is a magic number too, and you'd be kind of right... except that it's so widely used as to be somewhat of an exception to the rule.)

Bear in mind that the hash code is used as a first-step in determining equality only, and [is/should]never (be) used as a de-facto determination as to whether two objects are equal.

If two objects' hash codes are not equal then they are treated as not equal (because we assume that the unerlying implementation is correct - i.e. we don't second-guess that). If they have the same hash code, then they should then be checked for actual equality which, in your case, the null and the enum value will fail.

As a result - using zero is as good as any other value in the general case.

Sure, there will be situations, like your enum, where this zero is shared with a real value's hash code. The question is whether, for you, the miniscule overhead of an additional comparison causes problems.

If so, then define your own comparer for the case of the nullable for your particular type, and ensure that a null value always yields a hash code that is always the same (of course!) and a value that cannot be yielded by the underlying type's own hash code algorithm. For your own types, this is do-able. For others - good luck :)

Personally I find using nullable values a bit awkward and try to avoid them whenever I can. Your issue is just another reason. Sometimes they are very handy though but my rule of thumb is not to mix value types with null if possible simply because these are from two different worlds. In .NET framework they seem to do the same - a lot of value types provide TryParse method which is a way of separating values from no value (null).

In your particular case it is easy to get rid of the problem because you handle your own Season type.

(Season?)null to me means 'season is not specified' like when you have a webform where some fields are not required. In my opinion it is better to specify that special 'value' in the enum itself rather than use a bit clunky Nullable<T>. It will be faster (no boxing) easier to read (Season.NotSpecified vs null) and will solve your problem with hash codes.

Of course for other types, like int you can't expand value domain and to denominate one of the values as special is not always possible. But with int? hash code collision is much smaller problem, if at all.

But is there any reason why the hash code of null should be 0?

It could have been anything at all. I tend to agree that 0 wasn't necessarily the best choice, but it's one that probably leads to fewest bugs.

A hash function absolutely must return the same hash for the same value. Once there exists a component that does this, this is really the only valid value for the hash of null. If there were a constant for this, like, hm, object.HashOfNull, then someone implementing an IEqualityComparer would have to know to use that value. If they don't think about it, the chance they'll use 0 is slightly higher than every other value, I reckon.

at least for HashSet<>, it is not even possible to change the hash of null

As mentioned above, I think it's completely impossible full stop, just because there exist types which already follow the convention that hash of null is 0.

Tuple.Create( (object) null! ).GetHashCode() // 0
Tuple.Create( 0 ).GetHashCode() // 0
Tuple.Create( 1 ).GetHashCode() // 1
Tuple.Create( 2 ).GetHashCode() // 2