C# 我对IComparable和集合排序方法有问题
好的,我有一个类似于下面代码的场景,我有一个实现IComparable的父类和一个子类C# 我对IComparable和集合排序方法有问题,c#,.net,generics,inheritance,C#,.net,Generics,Inheritance,好的,我有一个类似于下面代码的场景,我有一个实现IComparable的父类和一个子类 class Parent : IComparable<Parent> class Child : Parent Child a = new Child(); Child b = new Child(); a.CompareTo(b); 您的类型实现了IComparable,而不是IComparable。比如说,如果“默认比较器(T).default找不到IComparable(T)泛型接口或
class Parent : IComparable<Parent>
class Child : Parent
Child a = new Child();
Child b = new Child();
a.CompareTo(b);
您的类型实现了
IComparable
,而不是IComparable
。比如说,如果“默认比较器(T).default找不到IComparable(T)泛型接口或类型T的IComparable接口的实现”,那么它将抛出InvalidOperationException。事实上,它找不到,其中T是子级。如果你试着把它列成一个列表
,你会发现它很好
编辑:或者(最好是IMO)实现
IComparable
。目前还不清楚一个孩子是否可以明智地与另一个孩子进行比较。实现IComparable
——即使该实现只是遵从基本实现——也会宣传可比性。我尝试了一下,遇到了同样的错误。我的猜测是,因为你有一个列表
,它在寻找实现IComparable
的人,而不是IComparable
如果将集合更改为
列表
,则一切似乎正常。或者,让孩子实现IComparable
(它可以委托给父母的实现)。我猜这与协方差/反方差有关。我之所以这么说,是因为这就像你说的那样失败了:
public class Parent : IComparable<Parent>
{
public int Age { get; set; }
public int CompareTo(Parent other)
{
return this.Age.CompareTo(other.Age);
}
}
public class Child : Parent
{
public string Name { get; set; }
}
我用以下代码对其进行了测试:
List<Child> c = new List<Child>();
c.Add(new Child { Age = 10, Name = "Alex" });
c.Add(new Child { Age = 6, Name = "Jack" });
c.Add(new Child { Age = 15, Name = "Bob" });
c.Sort();
List c=新列表();
c、 添加(新子女{Age=10,Name=“Alex”});
c、 添加(新子女{Age=6,Name=“Jack”});
c、 添加(新子女{Age=15,Name=“Bob”});
c、 排序();
您的示例显示“new List()”,我猜这是一个打字错误。。。你正在创建的列表上的实际泛型类型是什么?哦,对不起,是的,这是一个打字错误,我有一个列表l=新列表();我想我创建的泛型类型列表是很明显的。我们可以看看你的IComparable实现中的代码吗?@CalvinR是的,对不起。。。我想这可能是像List这样古怪的东西,但在我发表评论后意识到这是不可能的。不,我的比较很好,我只是使用存储在父类中的字符串成员变量的比较函数。现在完全更改了答案,检查了其他内容:)伙计,这绝对是垃圾,如果我在父类中实现非泛型IComparable,效果很好。是的,不幸的是,我不会很快改变我的集合以这种方式工作,所以我想我只需要在我想要排序的每个类中实现非泛型IComparable,或者只实现泛型IComparable。是的,我发现了同样的事情,我只是希望我仍然可以使用Icomparable的通用形式。
public class Parent : IComparable<Parent>
{
public int Age { get; set; }
public int CompareTo(Parent other)
{
return this.Age.CompareTo(other.Age);
}
}
public class Child : Parent
{
public string Name { get; set; }
}
public class Parent : IComparable
{
public int Age { get; set; }
public int CompareTo(object other)
{
Parent p = other as Parent;
return this.Age.CompareTo(p.Age);
}
}
public class Child : Parent
{
public string Name { get; set; }
}
List<Child> c = new List<Child>();
c.Add(new Child { Age = 10, Name = "Alex" });
c.Add(new Child { Age = 6, Name = "Jack" });
c.Add(new Child { Age = 15, Name = "Bob" });
c.Sort();