Tho*_*mas 9 c# icomparable .net-3.5
我正在尝试使用List.Sort()对对象列表进行排序,但在运行时它告诉我它无法比较数组中的元素.
无法比较数组中的两个元素
班级结构:
public abstract class Parent : IComparable<Parent> {
public string Title;
public Parent(string title){this.Title = title;}
public int CompareTo(Parent other){
return this.Title.CompareTo(other.Title);
}
}
public class Child : Parent {
public Child(string title):base(title){}
}
List<Child> children = GetChildren();
children.Sort(); //Fails with "Failed to compare two elements in the array."
Run Code Online (Sandbox Code Playgroud)
为什么我不能比较实现的基类的子类IComparable<T>?我可能错过了一些东西,但我不明白为什么不允许这样做.
编辑:应该澄清我的目标是.NET 3.5(SharePoint 2010)
Edit2:.NET 3.5是问题(见下面的答案).
Mar*_*ell 11
我假设这是.NET 4.0之前的.NET版本; 在.NET 4.0之后,它IComparable<in T>在许多情况下应该可以正常工作 - 但这需要4.0中的方差变化
列表是List<Child>- 所以排序它将尝试使用IComparable<Child>或IComparable- 但这两者都没有实现.您可以IComparable在该Parent级别实施,也许:
public abstract class Parent : IComparable<Parent>, IComparable {
public string Title;
public Parent(string title){this.Title = title;}
int IComparable.CompareTo(object other) {
return CompareTo((Parent)other);
}
public int CompareTo(Parent other){
return this.Title.CompareTo(other.Title);
}
}
Run Code Online (Sandbox Code Playgroud)
这将通过相同的逻辑object.