在值类上实现GetHashCode

时间:2012-02-15 09:56:40

标签: gethashcode iequatable

我有一个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
    }
}

1 个答案:

答案 0 :(得分:0)

由于Currency.Id似乎是唯一的,只要它是非零的integer我会选择

public override int GetHashCode()
{
    unchecked
    {
        return (Currency.Id*397) ^ Value.GetHashCode();
    }
}

Currency.Id设为非空stringGuid,以下方法可以解决问题

public override int GetHashCode()
{
    unchecked
    {
        return (Currency.Id.GetHashCode()*397) ^ Value.GetHashCode();
    }
}