vb.net - 为什么我的 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()
列表中的方法,这改变了行为,并且没有Nothing
s 传递给 IComparer。一位评论者发现 IComparers 预计会比较空值,这与数组的底层边界大于数组并Nothing
在其中静默包含 s 以生成预期的功能相结合。
解决方案
如果您只是在寻找调试帮助,请像这样启动 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
推荐阅读
- ndis - 复制 NetBufferListInfo 数组而不是调用 NdisCopySendNetBufferListInfo?
- spring-batch - 如何通过在春季批处理中拆分一组列来读取一个csv文件并写入不同的表
- ipc - 如何在systemverilog中获取信号量的大小(或)多少个键
- angular - 具有兼容范围选择器的 Ngx-mat-datetime-picker
- python - 固定大小的框架停留在窗口底部
- c# - 获取 AD 组成员的 DirectoryEntry 时如何处理特殊字符?
- node.js - 由于 Puppeteer 问题,无法安装 PagedJS
- botframework - 试图了解 ActivityProcessed 标志如何与 Bot Framework Composer 中的“开始新对话框”操作一起使用
- c# - 不会根据 xaml 网格中所有其他列的最大长度单元格宽度自动调整
- r - 选择和排序由 pivot_wider 操作创建的“数字列名称”