本文介绍了如何实现 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.它已经定义了.相反,您需要在您的 BankAccount 类上实现 IComparable.

You should not define IComparable yourself. It is already defined. Rather, you need to implement IComparable on your BankAccount class.

在您定义 class BankAccount 的地方,确保它实现了 IComparable 接口.然后编写BankAccount.CompareTo来比较两个对象的余额.

Where you defined the class BankAccount, make sure it implements the IComparable interface. Then write BankAccount.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;
    }
}

编辑以从评论中显示 Jeffrey L Whitledge 的解决方案:


Edit to show Jeffrey L Whitledge's solution from comments:

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

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

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

10-14 23:13