我有一个名为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(); –
嗯,我不这么认为这是什么产生...这就是为什么我试图找到一个好的解决方案... –