首页 > 解决方案 > 为什么我的 IComparer 排序出现空引用异常?

问题描述

我有一个自定义对象类型的列表说

Dim a As New List(Of CustomType)

填充实例。我有一个继承的比较器类

Public Class CustomTypeComparer
    Implements IComparer(Of CustomType)
    Public Function Compare(x As CustomType, y As CustomType) As Integer Implements IComparer(Of CustomType).Compare
        ...
    End Function
End Class

使用

a.Sort(New CustomTypeComparer)

方法。比较器的唯一方法Compare()会自动调用,但有时该方法会失败,因为x未定义或“未设置为对象的实例”。

我已经搜索了正在排序的列表以检查没有任何元素是 Nothing,通过a.Contains(Nothing)返回的手表确认False并使用查看对象其他部分的其他比较器进行检查,这些列表都没有问题,只有这个。

我怎样才能更深入地研究这个问题?人们可以就这个问题提供任何见解吗?

更新:

阅读框架的参考源码,列表排序方法使用的是底层Array.Sort()方法。从中得到提示,我尝试使用List.TrimExcess()列表中的方法,这改变了行为,并且没有Nothings 传递给 IComparer。一位评论者发现 IComparers 预计会比较空值,这与数组的底层边界大于数组并Nothing在其中静默包含 s 以生成预期的功能相结合。

标签: vb.netsortingnullreferenceexceptionicomparer

解决方案


如果您只是在寻找调试帮助,请像这样启动 CustomTypeComparer

Public Class CustomTypeComparer
    Implements IComparer(Of CustomType)
    Public Function Compare(x As CustomType, y As CustomType) As Integer Implements IComparer(Of CustomType).Compare
        If x Is Nothing Then
            Stop
        ElseIf y Is Nothing Then
            Stop

推荐阅读