3

我按降序排列了 SortedList。

public class MyComparer : IComparer<int>
    {
        public int Compare(int x, int y)
        {
            if (x.CompareTo(y) > 0)
                return -1;
            return 1;
        }
    }
class Program
{
        static void Main(string[] args)
        {
            SortedList<int, bool> myList = new SortedList<int, bool>(new MyComparer());
            myList.Add(10, true);
            bool check = myList[10];//In this place an exception "Can't find key" occurs
        }
}

当在没有我自己的 IComparer 的情况下创建 SortedList 时,代码可以正常工作并且不会发生异常。

4

1 回答 1

7

比较器实现无效;它违反了以下要求:

x.CompareTo(x) == 0 

当它试图找到给定键的完全匹配时,这会使排序列表混淆。

这是一个简单的修复:

public int Compare(int x, int y)
{  
    return y.CompareTo(x); // Reverses the in-built comparison.
}

但是,如果您想更普遍地解决这个问题,请考虑创建一个ReverseComparer<T>,例如此处提供的那个。

于 2011-11-19T09:47:00.237 回答