我有一個DataGridView
組件填充了SortableBindingList
,如SQL Server SDK Microsoft.SqlServer.Management.Controls
中所示。這個類也被用作XML序列化的根節點。c#SortableBindingList無法使用Object值對列進行排序
列表的成員是具有兩個原始字段和一個對象字段的類型。包含原始值的列按照人們所期望的排序。然而,排序包含對象字段列時,下面的異常被拋出:
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
實施中的某些內容?
在此先感謝。