[英]Custom class: Failed to compare two elements in the array
I have a list of abstract Class elements and when I try to sort it I get an exception with a message "Failed to compare two elements in the array" 我有一个抽象类元素的列表,当我尝试对它进行排序时,我得到一个异常,并显示消息“无法比较数组中的两个元素”
Abstract Class: 抽象类:
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);
}
Derived classes: 派生类:
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;
}
}
Can anybody please tell me what I'm doing wrong here? 谁能告诉我这里我做错了什么? I want to create List of nodes and call a method sort on it, thank you. 我想创建节点列表并调用方法排序,谢谢。
You don't have an IComparable<Node> on the base. 您的基础上没有IComparable <Node>。 Implement that, and delegate it to the ones you implemented for Interior and Leaf. 实现它,并将其委托给您为Interior和Leaf实现的那些。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.