List.Sort在C#:比较器被调用null对象

编程入门 行业动态 更新时间:2024-10-11 11:22:46
本文介绍了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对象

本文发布于:2023-11-30 06:08:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648975.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   List   Sort   null

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!