我有以下课程,它是统计分析包的一部分。
- The
MetricKey
对象用作字典键。
-
Decision
, MetricUnit
& Portfolio
都是枚举。
我必须重写相等运算符 (==) 才能使字典键匹配工作。我使用了以下指导http://msdn.microsoft.com/en-us/library/ms173147.aspx http://msdn.microsoft.com/en-us/library/ms173147.aspx。该指南说我应该重载我已经完成的 GetHashCode 方法,但我不明白将枚举转换为整数以进行 XOR (^) 操作的含义。我所做的是否有效,或者由于我的枚举整数值重叠,我会得到冲突的哈希码吗?:
public class MetricKey
{
public MetricKey(Decision decision, MetricUnit metricUnit, Portfolio portfolio)
{
Decision = decision;
Unit = metricUnit;
Portfolio = portfolio;
}
public Decision Decision { get; private set; }
public MetricUnit Unit { get; private set; }
public Portfolio Portfolio { get; private set; }
public static bool operator == (MetricKey a, MetricKey b)
{
if (ReferenceEquals(a, b))
return true;
if (((object) a == null) || ((object) b == null))
return false;
return a.Decision == b.Decision && a.Unit == b.Unit && a.Portfolio == b.Portfolio;
}
public static bool operator != (MetricKey a, MetricKey b)
{
return !(a == b);
}
public override bool Equals(System.Object obj)
{
if (obj == null)
return false;
var metricKey = obj as MetricKey;
if ((System.Object) metricKey == null)
return false;
return Decision == metricKey.Decision && Unit == metricKey.Unit && Portfolio == metricKey.Portfolio;
}
public bool Equals(MetricKey metricKey)
{
if ((object) metricKey == null)
return false;
return Decision == metricKey.Decision && Unit == metricKey.Unit && Portfolio == metricKey.Portfolio;
}
public override int GetHashCode()
{
return (int)Decision ^ (int)Unit ^ (int)Portfolio;
}
}
There is nothing wrong with the cast to int
- however, I would actually avoid xor - it is easy to create collisions with likely values of the enums (1,2,3, etc). Note that collisions don't break anything, but they can make things more expensive. I might use something like (picking at random taking inspiration from the C# compiler's handling of anonymous types):
int num = -1962473570;
num = (-1521134295 * num) + (int)Decision;
num = (-1521134295 * num) + (int)Unit;
return (-1521134295 * num) + (int)Portfolio;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)