2012-02-15 66 views
0

我有一個類的錢,我想知道這個值類的GetHashCode實現的最好的辦法是給那個$ 1!= 1€。具有針對貨幣*值是行不通的加權值。實現GetHashCode的一個值類

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

是答案有幫助? – nulltoken 2013-08-17 22:17:07

回答

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(); 
    } 
}