我很确定这是一个基本问题,但由于某种原因,我无法在谷歌上尽快找到它,所以我会在这里问.
我有一个MoneyType对象,它包含一个int(以美分为单位)和一个十进制(只是正常值)
这种类型继承了IComperable接口,可以进行比较,现在我在If语句中比较两个MoneyType:
if (invoice.GrossAmount == invoice.NetAmount)
{
//Something
}
Run Code Online (Sandbox Code Playgroud)
现在我应该覆盖什么方法或者我应该继承什么接口才能使它工作?由于这样做不会进入CompareTo()方法,因此它也不会进入.Equals方法,因此我处于亏损状态.
如果实现IComparable,则比实现该CompareTo方法.基于此实现,测试两个相等的金额执行如下:
if (invoice.GrossAmount.CompareTo(invoice.NetAmount) == 0)//the $ame amount of money
{..}
Run Code Online (Sandbox Code Playgroud)
直接比较"=="是指所描述的重载"=="运营商在这里.这是在MoneyType类中添加以下方法:
public static bool operator ==(MoneyType x, MoneyType y)
{
return x.CompareTo(y.NetAmount) == 0;//make use of the working IComparable implementation
}
Run Code Online (Sandbox Code Playgroud)
你也必须实现"!=".您还应该实现Equals方法(只需调用==运算符)和GetHashCode.
HTH,Lucian
| 归档时间: |
|
| 查看次数: |
95 次 |
| 最近记录: |