gpt4 book ai didi

vb.net - 检查 Visual Basic 中的列表索引处是否存在对象

转载 作者:行者123 更新时间:2023-12-02 03:26:35 26 4
gpt4 key购买 nike

我需要检查 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”不是检查该索引处是否存在某些内容的方法,那么什么是?

我正在参加应用程序开发类(class),我们正在使用 Visual Studio 2017 开发 Windows 窗体应用程序(如果有任何重要的话)。

最佳答案

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

  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

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

另请注意,在您发布的代码中,列表是一个 List(Of Integer)Integer 永远不可能是 Nothing,因此您检查的第二部分要么不需要,要么您应该检查 = 0 而不是 什么都没有

关于vb.net - 检查 Visual Basic 中的列表索引处是否存在对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53192975/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com