通过==比较CustomType

时间:2010-12-23 09:05:30

标签: c# .net

我很确定这是一个基本问题,但出于某种原因,我无法在Google上尽快找到它,所以我会在这里问。

我有一个MoneyType对象,它包含一个int(以美分为单位)和一个小数(只是正常值)

此类型继承了IComperable接口并且可以进行比较,现在我正在比较If语句中的两个MoneyType:

if (invoice.GrossAmount == invoice.NetAmount)
{
 //Something
}

现在我应该覆盖什么方法或者我应该继承什么接口才能使其工作?由于这样做不会进入CompareTo()方法,因此它也不会进入.Equals方法,因此我处于亏损状态。

5 个答案:

答案 0 :(得分:5)

如果您实施IComparable,则需要实施CompareTo方法。基于此实现,测试两个相等的金额执行:

if (invoice.GrossAmount.CompareTo(invoice.NetAmount) == 0)//the $ame amount of money
{..}

直接与“==”比较意味着重载“==”运算符,如here所述。这是在MoneyType类中添加以下方法:

public static bool operator ==(MoneyType x, MoneyType y) 
{
      return x.CompareTo(y.NetAmount) == 0;//make use of the working IComparable implementation
}

你也必须实现“!=”。您还应该实现Equals方法(只需调用==运算符)和GetHashCode

HTH, 卢西恩

答案 1 :(得分:3)

MSDN:

  

默认情况下,运算符==测试   通过确定引用相等   两个引用是否表明   相同的对象。

要更改此设置,您必须重载==和!=运算符。您可以查看here以获取有关MSDN的完整说明和示例。

答案 2 :(得分:2)

您必须覆盖==!=运算符。

public static bool operator ==(Invoice left, Invoice right)
{
    return Equals(left, right);
}

public static bool operator !=(Invoice left, Invoice right)
{
    return !Equals(left, right);
}

在* 排序 *该类型的对象列表的情况下实现IComaprable,并且* 订单 *不是平等

答案 3 :(得分:1)

尝试在MoneyType类中包含以下内容

        public static bool operator ==( MoneyType a, MoneyType b)
        {
            return a.cents == b.cents;
        }

        public static bool operator !=(MoneyType a, MoneyType b)
        {
            return a.cents != b.cents;
        }

答案 4 :(得分:0)

您可以使用完全可以接受的if (invoice.GrossAmount.Equals(invoice.NetAmount))