首页 > 解决方案 > 检查对象是否存在于 Visual Basic 中的列表索引处

问题描述

我需要检查对象是否存在于 Visual Basic 列表中的指定索引处。我所拥有的是

Dim theList As New List(Of Integer)({1,2,3})
If theList.Item(3) = Nothing Then
    'some code to execute if there is nothing at position 3 in the list

但是当我运行程序时,我得到 System.ArgumentOutOfRangeException,说索引超出范围。当然是,重点是看它是否存在。如果“= Nothing”不是检查该索引处是否存在某些东西的方法,那是什么?

我在我的应用程序开发课程中,我们正在使用 Visual Studio 2017 处理 Windows 窗体应用程序,如果有任何问题的话。

标签: vb.net

解决方案


如果您正在检查对象列表,则需要更改两件事。

  1. 什么都不检查的方法是使用Is Nothing.
  2. 您甚至不能尝试检查列表末尾之外的项目,因此您必须首先检查您要使用的索引是否小于列表中的项目数'

您应该将代码更改为

If theList.Items.Count > 3 AndAlso theList.Item(3) Is Nothing Then
    'some code to execute if there is nothing at position 3 in the list
End If

注意在语句中使用AndAlso而不是。这是必需的,因为它确保仅当列表中至少有 4 个项目时才会对项目 3 进行检查。AndIf

另请注意,在您发布的代码中,列表是List(Of Integer). Integer永远不可能,所以你检查的Nothing第二部分要么不需要,要么你应该检查= 0而不是Is Nothing


推荐阅读