在值类上实现 GetHashCode
我有一个 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
}
}
I have a class Money and I want to know what the best way of implementing GetHashCode on this value class would be give that $1 != €1. Having a weighted value against the currency * value is not going to work.
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
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于
Currency.Id
似乎是唯一的,只要它是一个非零整数
,我会选择Currency.Id
是否为非空string
或Guid
,以下内容即可解决问题As the
Currency.Id
seems unique, provided it's a non-zerointeger
I'd go withWould
Currency.Id
be a not-emptystring
or aGuid
, the following would do the trick