自定义类:无法比较数组中的两个元素

时间:2016-11-05 01:58:15

标签: c#

我有一个抽象类元素的列表,当我尝试对它进行排序时,我得到一个异常,并显示消息“无法比较数组中的两个元素”

抽象类:

public abstract class Node : IComparable<Leaf>, IComparable<Interrior>
{
    public virtual ulong Weight { get; set; }
    protected virtual int CompareWeights(Node node)
    {
        if (this.Weight < node.Weight) return -1;
        else if (this.Weight > node.Weight) return 1;
        else return 0;
    }
    public abstract int CompareTo(Interrior node);
    public abstract int CompareTo(Leaf node);
}

派生类:

public class Interrior : Node
{
    public Interrior(byte age, Node left, Node right)
    {
        Age = age;
        Left = left;
        Right = right;
        Weight = Left.Weight + Right.Weight;
    }
    public byte Age { get; }
    public Node Left { get; }
    public Node Right { get; }
    public override int CompareTo(Interrior node)
    {
        var result = CompareWeights(node);
        if (result == 0) result = this.Age < node.Age ? -1 : 1;
        return result;
    }
    public override int CompareTo(Leaf node)
    {
        var result = CompareWeights(node);
        if (result == 0) result = 1;
        return result;
    }
}
public class Leaf : Node
{
    public Leaf(byte symbol)
    {
        Symbol = symbol;
        Weight = 1;
    }
    public byte Symbol { get; }
    public override int CompareTo(Interrior node)
    {
        var result = CompareWeights(node);
        if (result == 0) result = -1;
        return result;
    }

    public override int CompareTo(Leaf node)
    {
        var result = CompareWeights(node);
        if (result == 0) result = this.Symbol < node.Symbol ? -1 : 1;
        return result;
    }
}

有人可以告诉我这里我做错了什么吗?我想创建节点列表并在其上调用方法排序,谢谢。

1 个答案:

答案 0 :(得分:0)

您没有IComparable&lt; Node&gt;在基地。实现它,并将其委托给您为Interior和Leaf实现的那些。