【问题标题】:Custom class: Failed to compare two elements in the array自定义类:无法比较数组中的两个元素
【发布时间】:2016-11-05 10:13:03
【问题描述】:

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

抽象类:

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;
    }
}

谁能告诉我我在这里做错了什么?我想创建节点列表并对其调用方法排序,谢谢。

【问题讨论】:

    标签: c#


    【解决方案1】:

    基础上没有 IComparable。实现它,并将其委托给您为 Interior 和 Leaf 实现的那些。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-30
      • 1970-01-01
      • 1970-01-01
      • 2016-06-19
      • 1970-01-01
      • 1970-01-01
      • 2021-05-06
      相关资源
      最近更新 更多