代码之家  ›  专栏  ›  技术社区  ›  David

Int32?与我相比

  •  10
  • David  · 技术社区  · 16 年前

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

    DataGridView Column sorting with Business Objects

    我无法使该解决方案适用于可空类型,因为它们没有实现IComparable。即使对于实现类似于字符串的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
    }
    
    2 回复  |  直到 9 年前
        1
  •  11
  •   Ruben    16 年前

    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));
    }
    

    没有必要去寻找 不可比 直接地,让排序方法自己进行排序。

        2
  •  4
  •   user110714 user110714    16 年前

    当比较可为空的类型时,您可以这样做吗。。。

    Int32? val1 = 30;
    Int32 val2 = 50;
    
    Int32 result = (val1 as IComparable).CompareTo(val2);
    
    推荐文章