首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Int32?使用IComparable

Int32?使用IComparable
EN

Stack Overflow用户
提问于 2009-08-11 21:21:25
回答 2查看 11.9K关注 0票数 10

我有一个数据源是BindingList的DataGridView。MyObj有一些可以为空的属性(比如int?那DateTime呢?)我想对我的绑定列表进行排序,这样当用户单击列标题时,DataGridView就可以对列进行排序。

经过一番挖掘,我发现并遵循了这个问题的答案(DataGridView Column sorting with Business Objects)。

我不能让这种解决方案适用于可为空的类型,因为它们不实现IComparable。即使对于像String这样实现IComparable的类,ApplySortCore(...)当字符串具有空值时失败。

对此有解决方案吗?或者我必须为“Int32”实现一个包装类?

例如

代码语言:javascript
复制
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
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2009-08-11 22:14:07

Nullable<int>可能不会实现IComparable,但int肯定会实现。Nullable<T>总是装箱为T (例如,当您转换为接口时,如IComparable,这是装箱转换)。因此,对可为空的属性进行比较/排序应该不是问题。

代码语言:javascript
复制
int? value = 1;
IComparable comparable = value; // works; even implicitly

因此,在顶部的示例中的检查不能正常工作。试试这个:

代码语言:javascript
复制
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(...)

代码语言:javascript
复制
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,只需让排序方法自己进行排序即可。

票数 11
EN

Stack Overflow用户

发布于 2009-08-11 22:00:31

当比较你的可空类型时,你可以这样做吗?

代码语言:javascript
复制
Int32? val1 = 30;
Int32 val2 = 50;

Int32 result = (val1 as IComparable).CompareTo(val2);
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1262996

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档