摘要 class 使用 IComparer

Abstract class using IComparer

我想创建和抽象 class 实现 IComparer 的 A,这样我就可以在子classes 中实现不同形式的比较,稍后再做:

A sortBy = new B();
A sortBy2 = new C();

我是 C# 的新手,我不太明白如何去做。我希望他们实施此方法的这种变体:

int IComparer<Flower>.Compare(Flower a, Flower b)
        {
            if (a.leaves > b.leaves)
                return 1;
            if (a.leaves< b.leaves)
                return -1;
            else
                return 0;
        }

但我不能对其使用抽象或覆盖,因为它无法编译。 你能告诉我如何实现这个吗? 谢谢

您可以尝试这样的操作:

abstract class Flower : IComparer<Flower>
{
    public int Leaves { get; set; }

    public int Compare(Flower x, Flower y)
    {
        if (x.Leaves > y.Leaves)
            return 1;
        if (x.Leaves < y.Leaves)
            return -1;
        else
            return 0;
    }
}

根据MSDN

Abstract classes are closely related to interfaces. They are classes that cannot be instantiated, and are frequently either partially implemented, or not at all implemented. One key difference between abstract classes and interfaces is that a class may implement an unlimited number of interfaces, but may inherit from only one abstract (or any other kind of) class. A class that is derived from an abstract class may still implement interfaces. Abstract classes are useful when creating components because they allow you specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed. They also version well, because if additional functionality is needed in derived classes, it can be added to the base class without breaking code.

上面定义的关键是加粗的文字。由于您希望比较以 class 为基础的 classes Flower class,因此 class、Flower 必须实现IComparer<Flower>界面。

当前代码 IComparer<Flower> 已明确实现 (SO: implicit vs explicit implementation)

隐式实现它使 abstractvirtual:

public abstract class A: IComparer<Flower>
{           
    public abstract int Compare(Flower a, Flower b);
}

public abstract class A: IComparer<Flower>
{           
    public virtual int Compare(Flower a, Flower b)
    {
        if (a.leaves > b.leaves)
            return 1;
        if (a.leaves< b.leaves)
            return -1;
        else
            return 0;
    }
}