我有一个Money类,我想知道在这个值类上实现GetHashCode的最佳方法是给$ 1!=€1。对货币*值加权值不起作用。
public class Money : System.IEquatable<Money>
{
public Money(Currency c, decimal val)
{
this.Currency = c;
this.Value = val;
}
public Currency Currency
{
get;
protected set;
}
public decimal Value
{
get;
protected set;
}
public override bool Equals(object obj)
{
Money m = obj as Money;
if (m == null){throw new System.ArgumentNullException("m");}
if(m.Currency.Id == this.Currency.Id)
{
if(m.Value == this.Value)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
public override int GetHashCode()
{
// What would be the best way of implementing this as €1 != $1
// Currency object contains 2 members, (int) Id and (string) symbol
}
}
答案 0 :(得分:0)
由于Currency.Id
似乎是唯一的,只要它是非零的integer
我会选择
public override int GetHashCode()
{
unchecked
{
return (Currency.Id*397) ^ Value.GetHashCode();
}
}
将Currency.Id
设为非空string
或Guid
,以下方法可以解决问题
public override int GetHashCode()
{
unchecked
{
return (Currency.Id.GetHashCode()*397) ^ Value.GetHashCode();
}
}