[英]Using For each loop without try-catch in Visual basic 2012
我有這個簡單的代碼:
Public Class Form1
Dim strFriends(4) As String
Private Sub ArrayElement_Click(sender As Object, e As EventArgs) Handles ArrayElement.Click
ClearList()
'Try
For Each item As String In strFriends
lstFriends.Items.Add(item)
Next
'Catch
'End Try
End Sub
Private Sub ClearList()
lstFriends.Items.Clear()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
strFriends(0) = "tom"
strFriends(1) = "kate"
strFriends(2) = "bill"
strFriends(3) = "harry"
End Sub
末級
如果try-catch被刪除,我會得到System.ArgumentNullException
是否必須使用try catch塊來使用For Each?
您要聲明一個5個元素的數組: Dim strFriends(4) As String
。 在Vb.NET中,數字表示數組上的最大索引,而不是元素數。
但是,您僅聲明4個元素。 因此,在foreach塊中,最后一個元素是字符串的默認值,即Nothing
,無法將其添加到列表視圖(或其他內容)中。
您可以像檢查其他建議一樣檢查數組上的每個項目是否有效,或者更正您的代碼。
試試這個,例如:
strFriends = New String() {"tom", "kate", "bill", "harry"}
您也可以使用列表:
Dim strFriends As New List(Of String)()
strFriends.Add("tom")
strFriends.Add("kate")
strFriends.Add("bill")
strFriends.Add("harry")
或者,您可以在添加之前檢查每個項目。 您也沒有填寫最后一個元素,這就是例外的原因。
If item IsNot Nothing Then
'add item
End If
不,每個循環都不需要try塊。 使用try-catch進行流控制是一個錯誤。 相反,請在添加元素之前進行測試以確保元素不為空。
嘗試這個:
If Not String.IsNullOrEmpty(item) Then
' Add item
End If
更新:
您可以檢查數組中是否包含任何內容,如下所示:
If strFriends.Length > 0 Then
' Do something with array
End If
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.