我已经在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循环控件的标头中全部具有相同的功能。
最简洁的答案是不。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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句