我有一个DataGridView
组件填充了SortableBindingList
,如SQL Server SDK Microsoft.SqlServer.Management.Controls
中所示。此类还用作XML序列化的根节点。
列表的成员是具有两个原始字段和一个对象字段的类型。包含原始值的列按人们期望的那样排序。但是,在对包含对象字段的列进行排序时,会抛出以下异常:
System.InvalidOperationException was unhandled
Message=Failed to compare two elements in the array.
Source=mscorlib
StackTrace:
at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
at System.Array.Sort[T](T[] array, Int32 index, Int32 length, IComparer`1 comparer)
at System.Collections.Generic.List`1.Sort(Comparison`1 comparison)
at Microsoft.SqlServer.Management.Controls.SortableBindingList`1.ApplySortCore(PropertyDescriptor prop, ListSortDirection direction)
at System.ComponentModel.BindingList`1.System.ComponentModel.IBindingList.ApplySort(PropertyDescriptor prop, ListSortDirection direction)
at System.Windows.Forms.BindingSource.ApplySort(PropertyDescriptor property, ListSortDirection sort)
...
InnerException: System.ArgumentException
Message=At least one object must implement IComparable.
Source=mscorlib
StackTrace:
at System.Collections.Comparer.Compare(Object a, Object b)
at Microsoft.SqlServer.Management.Controls.SortableBindingList`1.<>c__DisplayClass1.<GetComparisionDelegate>b__0(T t1, T t2)
at System.Array.FunctorComparer`1.Compare(T x, T y)
at System.Collections.Generic.ArraySortHelper`1.SwapIfGreaterWithItems(T[] keys, IComparer`1 comparer, Int32 a, Int32 b)
at System.Collections.Generic.ArraySortHelper`1.QuickSort(T[] keys, Int32 left, Int32 right, IComparer`1 comparer)
at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
从堆栈跟踪中可以清楚地看出,被比较的对象不是IComparable
- 除了它们之外。或者至少他们应该。有问题的课程如下:
using System;
using System.Xml.Serialization;
namespace myapp.xmlobjects {
[XmlType("error_after")]
public class ErrorAfterObject : IComparable<ErrorAfterObject> {
[XmlAttribute("hours")]
public int Hours { get; set; }
[XmlAttribute("minutes")]
public int Minutes { get; set; }
public ErrorAfterObject() { }
public ErrorAfterObject(int hours, int minutes) {
this.Hours = hours;
this.Minutes = minutes;
}
public override string ToString() {
return string.Format("{0} hr {1} min", this.Hours, this.Minutes);
}
public int CompareTo(ErrorAfterObject other) {
return (this.Hours*60 + this.Minutes).CompareTo(other.Hours*60 + other.Minutes);
}
}
}
作为一个完整性检查,我在数据绑定后添加了以下调试代码:
Console.WriteLine(myGridView.Rows[0].Cells[2].ValueType.ToString());
以我期望的方式返回myapp.xmlobjects.ErrorAfterObject
。
可能有助于解决问题的三个问题:我的对象是否被输入为无法比拟的东西?是否可以准确检查正在比较的对象类型?我是否遗漏了IComparable
实施中的内容?
提前致谢。
答案 0 :(得分:2)
事实证明,IComparable
和IComparable<T>
不是一回事。用以下代码替换类定义:
public class ErrorAfterObject : IComparable
和CompareTo方法:
public int CompareTo(object other) {
if(this.GetType() != other.GetType()) {
return Comparer.Default.Compare(this, other);
}
return (this.Hours*60 + this.Minutes).CompareTo(
((ErrorAfterObject)other).Hours*60 + ((ErrorAfterObject)other).Minutes);
}
按照预期工作。