【问题标题】:Sorting non IComparable objects对非 IComparable 对象进行排序
【发布时间】:2011-02-20 14:03:48
【问题描述】:

根据文档:

System.Array.Sort<T> - 使用 System.Array 的每个元素的 System.IComparable 通用接口实现对整个 System.Array 中的元素进行排序。

今天我发现,这段代码正在编译,没有任何错误和警告:

A []arr = new A[10];//A is not inheriting from IComparable !!

//initializing elements of arr
...

System.Array.Sort<A>(arr);

执行后出现运行时错误。

那么为什么要编译这段代码呢?我不是 C# 的大专家,但我知道 C# 泛型支持约束语法。为什么 Array.Sort 不使用约束?

【问题讨论】:

    标签: c# arrays generics sorting constraints


    【解决方案1】:

    编译中,因为T 没有限制它必须实现IComparable&lt;T&gt;

    我认为文档有点混乱,因为数组元素实际上不必为与调用相同的T 实现IComparable&lt;T&gt;。例如,这很好用:

    using System;
    
    class Test
    {
        static void Main()
        {
            object[] objects = { "d", "b", "c", "a" };        
            Array.Sort<object>(objects);
        }
    }
    

    我认为只说元素必须“以某种方式”相互比较更为明智。例如,这很好,即使没有实现 generic IComparable 接口:

    using System;
    
    class A : IComparable
    {
        private readonly int value;
    
        public A(int value)
        {
            this.value = value;
        }
    
        public int CompareTo(object other)
        {
            // Just cast for now...
            return value.CompareTo(((A)other).value);
        }
    }
    
    class Test
    {
        static void Main()
        {
            object[] objects = { new A(5), new A(3), new A(4) };
            Array.Sort<object>(objects);
        }
    }
    

    【讨论】:

    • 所以不对类型使用约束的目的是为了能够对实现IComparable但不实现IComparable&lt;T&gt;的对象进行排序?
    • @Ashot:据我所知,是的。
    猜你喜欢
    • 2015-01-08
    • 2021-02-07
    • 1970-01-01
    • 2013-12-05
    • 2015-02-27
    • 2017-06-07
    • 2018-02-13
    • 2019-11-24
    • 1970-01-01
    相关资源
    最近更新 更多