我一直在 Vb.net 中编写一些软件,并且我在程序中遇到了这样的情况,如果我可以在 for 循环的 header 中放置一个 if 语句,那就最好了。
例如,在java中,我可以像这样实现我所需要的..
for (int I = 0; myArray[I].compareTo("") == 0; I ++)
{
'code here
}
不幸的是,在 Vb.net 中,我所知道的就是在 for 循环中将一个数字增加到给定数字。但是我知道,我需要做的事情可以使用 for 循环内的 if 测试来完成
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 循环 header 内的 if 条件(而不是比较两个数字)?
更新:为了回应 @Olivier Jacot-Decombes 的回答,我只是想澄清一下,我知道 while 循环用于测试循环中的 if 条件,但它们失去了for循环具有自动递增功能。在 Java 中,for 循环可以完成这两件事。这就是为什么我想知道 Vb.net 是否在 for 循环控件的 header 中具有相同的功能。
最佳答案
改用 While 循环
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
不同)确保快捷方式评估。 IE。如果第一个条件不为 True
,则不会评估第二个条件。我们在这里需要这个,否则数组将抛出“索引越界”异常。另请注意,数组索引从 0 到 array.Length - 1。
但您也可以使用 Exit For
退出 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 statement允许您在循环结束时测试条件。
关于java - 在 Vb.net 中使用 If-Statement 作为 For-Loop 的测试条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38859373/