List.Sort在C#:比较器被调用null对象 [英] List.Sort in C#: comparer being called with null object

查看:1858
本文介绍了List.Sort在C#:比较器被调用null对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是内置有一个自定义比较C#List.Sort功能。

I am getting strange behaviour using the built-in C# List.Sort function with a custom comparer.

有关某种原因,它有时调用比较器类的比较方法一个空对象作为参数之一。但是如果我检查与调试器列表中有集合中没有空对象

For some reason it sometimes calls the comparer class's Compare method with a null object as one of the parameters. But if I check the list with the debugger there are no null objects in the collection.

我的比较器类看起来是这样的:

My comparer class looks like this:

public class DelegateToComparer<T> : IComparer<T>
{
    private readonly Func<T,T,int> _comparer;

    public int Compare(T x, T y)
    {
        return _comparer(x, y);
    }

    public DelegateToComparer(Func<T, T, int> comparer)
    {
        _comparer = comparer;
    }
}

这允许委托传递到列表中。排序方式,如:

This allows a delegate to be passed to the List.Sort method, like this:

mylist.Sort(new DelegateToComparer<MyClass>(
    (x, y) => { 
         return x.SomeProp.CompareTo(y.SomeProp); 
     });

所以上面的代表将抛出一个空引用异常的 X 的参数,即使没有的 MYLIST 的是空的。

So the above delegate will throw a null reference exception for the x parameter, even though no elements of mylist are null.

更新:是我绝对相信这是参数的 X 的抛出空引用异常

UPDATE: Yes I am absolutely sure that it is parameter x throwing the null reference exception!

更新:除了使用框架的List.Sort的方法,我想自定义排序方法(即新冒泡()排序(MYLIST)的),并问题走了,正如我嫌,List.Sort方法传递空到比较器由于某种原因。

UPDATE: Instead of using the framework's List.Sort method, I tried a custom sort method (i.e. new BubbleSort().Sort(mylist)) and the problem went away. As I suspected, the List.Sort method passes null to the comparer for some reason.

推荐答案

此问题当比较功能是不相符的发生,使得x< Y不总是意味着Y'LT; X。在你的榜样,你应该检查如何SomeProp类型的两个实例进行比较。

This problem will occur when the comparison function is not consistent, such that x < y does not always imply y < x. In your example, you should check how two instances of the type of SomeProp are being compared.

下面是重现该问题的例子。在这里,它是由病理引起的比较功能compareStrings。这是依赖于列表的初始状态:如果你改变了最初的以C,B,A,那么有没有例外

Here's an example that reproduces the problem. Here, it's caused by the pathological compare function "compareStrings". It's dependent on the initial state of the list: if you change the initial order to "C","B","A", then there is no exception.

我不会把这个在排序函数中的错误 - 它只是一个要求,即比较函数是一致的。

I wouldn't call this a bug in the Sort function - it's simply a requirement that the comparison function is consistent.

using System.Collections.Generic;

class Program
{
    static void Main()
    {
        var letters = new List<string>{"B","C","A"};

        letters.Sort(CompareStrings);
    }

    private static int CompareStrings(string l, string r)
    {
        if (l == "B")
            return -1;

        return l.CompareTo(r);
    }
}

这篇关于List.Sort在C#:比较器被调用null对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆