如何在for循环结束时触发命令?

时间:2018-02-22 12:55:05

标签: vb.net loops if-statement

我有一个带有If条件的for循环,我想只在循环结束并且没有触发If条件时才触发命令。

2 个答案:

答案 0 :(得分:0)

您可以使用ReturnReturn会立即退出该功能。这是一个例子:

 Dim a As Byte
 For a = 10 To 20
   Console.WriteLine("value of a: {0}", a)
   If a= "20" Then
      CoolFunction()
      Return
   End If
 Next
 MsgBox("u will never see this msg! maybe if you edit the if condition...")

如果If条件被触发,那么它将不会执行循环下的代码。如果If条件没有被触发,那么循环中的所有内容都将被执行。

您也可以使用Boolean。这不会“杀死”循环中的所有内容。

 Dim a As Byte
 Dim EvenTriggered As Boolean = False
 For a = 10 To 20
   Console.WriteLine("value of a: {0}", a)
   If a= "20" Then
      CoolFunction()
      EventTriggered = True
   End If
 Next
 If EventTriggered = False Then
     MsgBox("u will never see this msg! maybe if you edit the if condition...")
 End IF

答案 1 :(得分:0)

你需要保持旗帜。默认情况下将其设置为false,当执行if语句时,将标志设置为true。

Dim didIfExecute As Boolean = False

For ...
   If ... Then
      didIfExecute = True
   End If
Next

If Not didIfExecute Then
   ...
End If