[英]Using If-Statement as test condition for For-Loop in Vb.net
我已經在Vb.net中編寫了一些軟件,並且在程序中到了一個關鍵點,那就是如果可以將if語句放在for循環的標題中,那將是最好的。
例如,在Java中,我可以像這樣實現我所需要的。
for (int I = 0; myArray[I].compareTo("") == 0; I ++)
{
'code here
}
不幸的是,在Vb.net中,我所知道的唯一方法是在for循環中將一個數字遞增到給定的數字。 但是我知道,我需要做的事可以在for循環中使用if-test來完成
For I as Integer = 0 To myArray.length 'only possible test is comparison between two ints
'code here
If myArray(I).compareTo("") <> 0 Then
Exit For
End If
Next
這樣做不是什么大不了的事情,但是如果有一種方法可以將其簡化為for循環控制,那么我想知道現在和將來的參考。
所以我的問題是,是否可以在Vb.net的for循環頭中檢查if條件(而不是比較兩個數字)?
更新:為了響應@Olivier Jacot-Descombes的回答,我只是想澄清一下,我知道while循環用於測試循環中的if條件,但是它們失去了for循環所具有的自動遞增功能。 在Java中,for循環可以同時實現這兩個功能。 這就是為什么我想知道Vb.net是否以某種方式在for循環控件的標頭中全部具有相同的功能。
改用While-Loop
Dim i As Integer = 0
While i < myArray.Length AndAlso String.IsNullOrEmpty(myArray(i))
'Code here
i += 1
End While
在VB中,字符串可以為空( ""
)或Nothing
(在C#中為null
)。 為了應付兩種情況,請使用String.IsNullOrEmpty(s)
。
AndAlso
(與And
不同)可確保快捷方式評估。 即,如果第一個條件不為True
,則將不評估第二個條件。 我們在這里需要這個,否則數組將拋出“索引超出范圍”異常。 還要注意,數組索引從0到array.Length-1。
但是您也可以使用Exit For
從For循環中Exit For
For I As Integer = 0 To myArray.Length-1
'code here
If Not String.IsNullOrEmpty(myArray(I)) Then
Exit For
End If
Next
但是退出這樣的循環會使代碼不可讀。 問題在於,For循環現在具有2個出口點,並且在不同位置定義了循環和出口條件。
還有一個Do ... Loop語句,允許您在循環結束時測試條件。
最簡潔的答案是不。 Visual Basic語言沒有C / java樣式的for()
循環。
更長的答案是,根據您的需要,您甚至可能不需要循環。
Dim a = {"a", Nothing, "", "b"}
' this will print from 0 to 1, but Array.IndexOf returns -1 if value is not found
For i = 0 To Array.IndexOf(a, "") - 1
Debug.Print(i & "")
Next
For Each item In a : If item = "" Then Exit For ' this is actually 2 lines separated by :
Debug.Print("'{0}'", item)
Next
For Each item In a.TakeWhile(Function(s) s > "") ' TakeWhile is a System.Linq extension
Debug.Print("'{0}'", item)
Next
a.TakeWhile(Function(s) s > "").ToList.ForEach(AddressOf Debug.Print) ' prints a
a.TakeWhile(Function(s) s > "").ToList.ForEach(Sub(s) Debug.Print(s)) ' prints a
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.