我有一個名爲Color類,它實現以下重寫:字典和緩存
public override Int32 GetHashCode()
{
unchecked
{
Int32 hash = 23;
hash = (hash * 37) + m_Changes.GetHashCode();
hash = (hash * 37) + m_Blue;
hash = (hash * 37) + m_Green;
hash = (hash * 37) + m_Random;
hash = (hash * 37) + m_RandomBlue;
hash = (hash * 37) + m_RandomGreen;
hash = (hash * 37) + m_RandomRed;
hash = (hash * 37) + m_Red;
return hash;
}
}
我想緩存以減少計算結果來:
public static Color Average(Color left, Color right, Double weight)
{
Color value;
Int32 key = left.GetHashCode()^right.GetHashCode()^weight.GetHashCode();
if (!s_Averages.TryGetValue(key, out value))
{
Double complement = 100.0 - weight;
Int32 red = (Int32)(((left.Red * complement) + (right.Red * weight))/100.0);
Int32 green = (Int32)(((left.Green * complement) + (right.Green * weight))/100.0);
Int32 blue = (Int32)(((left.Blue * complement) + (right.Blue * weight))/100.0);
Int32 random = (Int32)(((left.Random * complement) + (right.Random * weight))/100.0);
Int32 randomRed = (Int32)(((left.RandomRed * complement) + (right.RandomRed * weight))/100.0);
Int32 randomGreen = (Int32)(((left.RandomGreen * complement) + (right.RandomGreen * weight))/100.0);
Int32 randomBlue = (Int32)(((left.RandomBlue * complement) + (right.RandomBlue * weight))/100.0);
value = new Color(red, green, blue, randomRed, randomGreen, randomBlue, random, (left.Changes || right.Changes));
s_Averages.Add(key, value);
}
return value;
}
結果當我在屏幕上繪製平均顏色時,出現錯誤像素,效果不佳。如果我恢復的方法無高速緩存的版本,一切工作正常:
public static Color Average(Color left, Color right, Double weight)
{
Double complement = 100.0 - weight;
Int32 red = (Int32)(((left.Red * complement) + (right.Red * weight))/100.0);
Int32 green = (Int32)(((left.Green * complement) + (right.Green * weight))/100.0);
Int32 blue = (Int32)(((left.Blue * complement) + (right.Blue * weight))/100.0);
Int32 random = (Int32)(((left.Random * complement) + (right.Random * weight))/100.0);
Int32 randomRed = (Int32)(((left.RandomRed * complement) + (right.RandomRed * weight))/100.0);
Int32 randomGreen = (Int32)(((left.RandomGreen * complement) + (right.RandomGreen * weight))/100.0);
Int32 randomBlue = (Int32)(((left.RandomBlue * complement) + (right.RandomBlue * weight))/100.0);
return (new Color(red, green, blue, randomRed, randomGreen, randomBlue, random, (left.Changes || right.Changes)));
}
這隻能意味着他們鍵入我生成使用的GetHashCode不是唯一的。我如何管理這種緩存爲我的顏色平均數獲取唯一鍵值?
爲什麼究竟是什麼? D: –
舉例:爲什麼你認爲這是一個合適的和唯一的密鑰?:Int32 key = left.GetHashCode()^ right.GetHashCode()^ weight.GetHashCode(); –
嗯,我不這麼認爲這是什麼產生...這就是爲什麼我試圖找到一個好的解決方案... –