[英]Int32? with IComparable
我有一個DataGridView,其數據源是BindingList。 MyObj有一些可以為空的屬性(比如int?和DateTime?)我想實現對綁定列表的排序,因此DataGridView可以在用戶點擊列標題時對列進行排序。
經過一番挖掘,我發現並遵循了這個問題的答案( 使用Business Objects進行DataGridView列排序 )。
我無法讓這個解決方案適用於Nullable類型,因為它們沒有實現IComparable。 即使對於像String這樣實現IComparable的類,當String具有空值時,ApplySortCore(...)也會失敗。
這有解決方案嗎? 或者我是否必須為“Int32”實現包裝類? ?
例如
public class Int32Comparable : IComparable
{
public int? Value { get; set; }
#region IComparable<int?> Members
public int CompareTo(object other)
{
// TODO: Implement logic here
return -1;
}
#endregion
}
Nullable<int>
可能沒有實現IComparable
,但肯定是int
。 並且Nullable<T>
總是框到T
(例如當你轉換為接口時,例如IComparable
,這是一個裝箱轉換)。 因此,對可空屬性進行比較/排序應該不是問題。
int? value = 1;
IComparable comparable = value; // works; even implicitly
因此,頂部樣本的檢查無法正常工作。 試試這個:
Type interfaceType = prop.PropertyType.GetInterface("IComparable");
// Interface not found on the property's type. Maybe the property was nullable?
// For that to happen, it must be value type.
if (interfaceType == null && prop.PropertyType.IsValueType)
{
Type underlyingType = Nullable.GetUnderlyingType(prop.PropertyType);
// Nullable.GetUnderlyingType only returns a non-null value if the
// supplied type was indeed a nullable type.
if (underlyingType != null)
interfaceType = underlyingType.GetInterface("IComparable");
}
if (interfaceType != null)
// rest of sample
還有一個補充:如果你想要null值(字符串和可空類型),你可以嘗試重新實現SortCore(...)
:
protected override void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction)
{
IEnumerable<MyClass> query = base.Items;
if (direction == ListSortDirection.Ascending)
query = query.OrderBy( i => prop.GetValue(i) );
else
query = query.OrderByDescending( i => prop.GetValue(i) );
int newIndex = 0;
foreach (MyClass item in query)
{
this.Items[newIndex] = item;
newIndex++;
}
this.OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
}
沒有必要直接查找IComparable
,只需讓排序方法自行排序。
在比較你的可空類型時,你可以做這樣的事情......
Int32? val1 = 30;
Int32 val2 = 50;
Int32 result = (val1 as IComparable).CompareTo(val2);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.