我有一个数据源是BindingList的DataGridView。MyObj有一些可以为空的属性(比如int?那DateTime呢?)我想对我的绑定列表进行排序,这样当用户单击列标题时,DataGridView就可以对列进行排序。
经过一番挖掘,我发现并遵循了这个问题的答案(DataGridView Column sorting with Business Objects)。
我不能让这种解决方案适用于可为空的类型,因为它们不实现IComparable。即使对于像String这样实现IComparable的类,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
}发布于 2009-08-11 22:14:07
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,只需让排序方法自己进行排序即可。
发布于 2009-08-11 22:00:31
当比较你的可空类型时,你可以这样做吗?
Int32? val1 = 30;
Int32 val2 = 50;
Int32 result = (val1 as IComparable).CompareTo(val2);https://stackoverflow.com/questions/1262996
复制相似问题