![](/img/trans.png)
[英]Is it possible to combine hash codes for private members to generate a new hash code?
[英]How should you combine the hash codes of class members?
為類生成哈希碼時,可以使用該類成員的哈希碼嗎? 這是一個示例類:
class Sample
{
private readonly string _strA, _strB;
public Sample(string strA, string strB)
{
this._strA = strA;
this._strB = strB;
}
public override int GetHashCode()
{
return (this._strA + "###" + this._strB).GetHashCode();
}
}
我認為,只要_strA或_strB都不包含字符串“ ###”,此方法都將起作用。 我不確定,因為我不知道如何在字符串上生成哈希碼的細節。
我在創建兩個數字的哈希碼的帖子中看到了一個解決方案,可以根據自己的目的進行調整,但是我認為我的解決方案更簡單(只要兩個字符串都不包含“ ###”)。
如果您有多個字段有助於對象的總體哈希碼,則一種簡單而有效的方法是:
public override int GetHashCode()
{
int hash = 17;
hash = hash*23 + field1.GetHashCode();
hash = hash*23 + field2.GetHashCode();
hash = hash*23 + field3.GetHashCode();
// And so on for all applicable fields.
// field1, field2 and field3 are all class field members.
return hash;
}
更好的方法是使用類似於Times 33 hash的數學方法來組合哈希碼。 在您當前的代碼中,每次調用GetHashCode
都會創建一個臨時字符串,這可能會導致性能下降。
public override int GetHashCode()
{
// omit null-coalesce if we know them to be non-null
return (33 * (this._strA ?? "").GetHashCode())
+ (this._strB ?? "").GetHashCode();
}
如果您的課程確實是不可變的,則預先計算哈希碼可能值得4個字節:
private readonly int _hash;
public Sample(string strA, string strB)
{
this._strA = strA;
this._strB = strB;
this._hash = (33 * (this._strA ?? "").GetHashCode())
+ (this._strB ?? "").GetHashCode();
}
public override int GetHashCode()
{
return this._hash;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.