如何实现IComparable接口? [英] How to Implement IComparable interface?

查看:152
本文介绍了如何实现IComparable接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用类的实例填充数组:

I am populating an array with instances of a class:

BankAccount[] a;
. . .

a = new BankAccount[]
{
    new BankAccount("George Smith", 500m),
    new BankAccount("Sid Zimmerman", 300m)
};

一旦我填充这个数组,我想按余额金额对它进行排序。为了做到这一点,我希望能够使用 IComparable 检查每个元素是否可排序。

我需要使用接口来做到这一点。到目前为止,我有以下代码:

Once I populate this array, I would like to sort it by balance amounts. In order to do that, I would like to be able to check whether each element is sortable using IComparable.
I need to do this using interfaces. So far I have the following code:

public interface IComparable
{
    decimal CompareTo(BankAccount obj);
}

但我不确定这是否是正确的解决方案。有什么建议吗?

But I'm not sure if this is the right solution. Any advice?

推荐答案

你不应该自己定义IComparable。它已经定义了。

You should not define IComparable yourself. It is already defined.

相反,您需要在 BankAccount 实施 IComparable class。

Rather, you need to implement IComparable on your BankAccount class.

在你定义类BankAccount 的地方,确保它实现了IComparable接口

Where you defined the class BankAccount, make sure it implements the IComparable interface

然后写 BankAccout.CompareTo 来比较两个对象的余额。

Then write BankAccout.CompareTo to compare the balance amounts of the two objects.

编辑

public class BankAccount : IComparable<BankAccount>
{
    [...]

    public int CompareTo(BankAccount that)
    {
        if (this.Balance >  that.Balance) return -1;
        if (this.Balance == that.Balance) return 0;
        return 1;
    }
}






编辑2 以显示Jeffrey L Whitledge的好答案:


Edit 2 to show Jeffrey L Whitledge's good answer:

public class BankAccount : IComparable<BankAccount>
{
    [...]

    public int CompareTo(BankAccount that)
    {
        return this.Balance.CompareTo(that.Balance);
    }
}

这篇关于如何实现IComparable接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆