0

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

1 回答 1

0

看起来很独特,只要Currency.Id它是非零的,integer我会选择

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

Currency.Id将是一个非空string或 a Guid,下面会做的伎俩

public override int GetHashCode()
{
    unchecked
    {
        return (Currency.Id.GetHashCode()*397) ^ Value.GetHashCode();
    }
}
于 2012-02-15T10:07:06.240 回答