Nullable<int>
可能无法实施
IComparable
,但肯定
int
Nullable<T>
总是把盒子装到盒子里
T
(例如,当您强制转换到接口时,例如
,这是装箱转换)。因此,对可空属性进行比较/排序应该不是问题。
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
还有一个补充:如果您希望空值也能工作(字符串和可空类型),您可以尝试重新实现
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));
}
没有必要去寻找
不可比
直接地,让排序方法自己进行排序。