![](/img/trans.png)
[英]Shouldn't my nhibernate mapping take care of this? Error: not-null property reference a null or transient value
[英]Should GetHashCode() method take care about null value given as parameter?
在一些C#代碼中,我使用linq
GroupBy<TSource, TKey>()
方法和自定義IEqualityComparer<T>
。
GroupBy(x => x.SomeField, new FooComparer());
我用作分組鍵的字段可以為null
。 因此,我必須在Equals()
方法中添加一些null
檢查:
public bool Equals(Foo x, Foo y)
{
if (x == null && y == null)
return true;
else if (x == null && y != null)
return false;
else if (x != null && y == null)
return false;
else
return x.Id == y.Id;
}
問題是:我應該在GetHashCode()
函數中做同樣的事情嗎?
public int GetHashCode(Foo obj)
{
if (obj == null) //is this really needed ?
return default(int); //
else
return obj.Id;
}
我不明白的東西:即使使用GroupBy()
方法中提供的null鍵,也不會在obj參數中使用null
對象調用GetHashCode()
。 有人可以解釋一下為什么嗎? (它只是“純粹的機會”,因為GroupBy()
的實現方式和我給它的元素的順序?)
編輯:
正如caerolus指出的那樣,在GroupBy()
實現中進行了一些特殊檢查。
我檢查了ILSpy
, GroupBy()
是用Lookup<TKey, TElement>
這是一個重要的功能:
internal int InternalGetHashCode(TKey key)
{
if (key != null)
{
return this.comparer.GetHashCode(key) & 2147483647;
}
return 0;
}
根據IEqualityComparer<T>.GetHashCode
的文檔 :
ArgumentNullException
obj
的類型是引用類型,obj
是null 。
所以這是該界面合同的一部分,因此你應該關心。 如果obj
為null
則通過拋出ArgumentNullException
實現它。
您應該始終堅持使用界面,即使您懷疑或可以證明代碼永遠不會觸及您不關心的部分。 稍后的更改可能會引入依賴於該行為的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.