代码之家  ›  专栏  ›  技术社区  ›  J Collins

为什么在我的icomparer排序中会出现空引用异常?

  •  1
  • J Collins  · 技术社区  · 6 年前

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

    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 未定义或“未设置为对象的实例”。

    我已经搜索了正在排序的列表,以检查没有一个元素是空的,用手表确认 a.Contains(Nothing) 哪些回报 False 使用其他比较器检查对象的其他部分,没有一个列表有问题,只有这一个。

    我怎样才能更深入地研究这个问题呢?人们在这个问题上有什么见解吗?

    更新:

    在读取框架的引用源代码时,list sort方法使用 Array.Sort() 方法。从中得到提示,我尝试使用 List.TrimExcess() 方法,这改变了行为,并且没有 Nothing S被传给了iComparer。一个评论者发现,icomparer需要比较nulls,这与数组的底层绑定大于数组并静默地具有 没有什么 以生成预期的功能。

    1 回复  |  直到 6 年前
        1
  •  0
  •   dbasnett    6 年前

    如果您只是在寻找调试帮助,请像这样启动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