C#接口 - 如何实现IComparable? [英] C# Interfaces - How to Implement IComparable?

查看:254
本文介绍了C#接口 - 如何实现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的

我要做到这一点使用的接口。到目前为止,我有这样的:

I need to do this using interfaces. So far I have this:

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.

相反,你需要的实施的IComparable的在你的的BankAccount 类。

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 以显示杰弗里大号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);
    }
}

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

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