vb.net - 检查对象是否存在于 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 窗体应用程序,如果有任何问题的话。
解决方案
如果您正在检查对象列表,则需要更改两件事。
- 什么都不检查的方法是使用
Is Nothing
. - 您甚至不能尝试检查列表末尾之外的项目,因此您必须首先检查您要使用的索引是否小于列表中的项目数'
您应该将代码更改为
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 进行检查。And
If
另请注意,在您发布的代码中,列表是List(Of Integer)
. Integer
永远不可能,所以你检查的Nothing
第二部分要么不需要,要么你应该检查= 0
而不是Is Nothing
。
推荐阅读
- c++ - 多管道,C++
- c++ - “struct seq<0, 1, 2>{}”数据类型是什么意思?
- alfresco - Alfresco - 将收件人姓名添加到工作流通知电子邮件模板
- python - 与 eval() 相对的 Python
- rest - 如果资源正在使用且无法删除,请更正 Delete API 的 HTTP 响应代码
- c# - 如果继承,实体框架返回错误的对象类型
- flutter - 我正在尝试将动态 url 加载为初始 url bt 它没有加载到 webview 中。如果我将 url 放入 tem var 并将 temp 用作初始 url,那么它将起作用
- javascript - Javascript Strigify Push 和 Shift 给了我错误
- python - 用python将所有浮点数乘以一个数字
- reactjs - react-router-dom 嵌套路由和重定向