【发布时间】: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#