(微优化)- 退出函数或让它 运行 通过所有代码
(Micro Optimisation) - Exit function or let it run through all code
我很好奇Exit Sub, Exit Function
,编码时是否应该避免其他?我在不同的地方读到这是一种不好的做法,如果可能的话,你应该避免它。
我在下面提供了一个函数来证明我的意思:
Function Test()
Dim X As Integer
X = 5
If X = 10 Then
Test = True
Exit Function
Else
Test = False
Exit Function
End If
End Function
In the case above, the Exit Function
isn't necessary since the entire code will be able to finish the entire routine without an issue. But by adding it, will it cause some issues?
这取决于代码的当前上下文。如果你在一个块内(循环、Sub 或函数等)并试图离开,Exit Statement 会很好。
Return Statement will also work the same as a Exit Function
or Exit Sub
, see the answer to this SO question。但就我个人而言,当我希望 return 控制调用代码但对 return.
没有任何价值时,我更喜欢函数中的 exit 语句
您使用的样式来自 VB5 和 VBA 时代,不支持 Return
语句,我们需要将 return 值直接分配给函数姓名。在 VB.NET 中,您应该始终使用 Return
赋值。 Return
将在一个语句中执行赋值和退出调用。
关于您的特定示例,我的印象是 Exit Function
语句只不过是对最近的 End Function
行执行 GoTo
。因此,您的案例中的这些语句是多余的,可能会被编译器删除(对此不确定)。
请注意,从代码可读性的角度来看,Exit
语句变成了噩梦。我最近成为这个特殊问题的受害者。 Visual Basic 是一种冗长的语言,Exit
语句不会被 reader 注意到。结构化的 If/Else
块可读性更高。
几乎在每种情况下,都有一种 "better" 方法而不是使用 Exit Function
。
以下示例将给出相同的结果,但更短,而且在我看来更清晰。
Function Test() As Boolean
Dim X As Integer
X = 5
Return (X = 10)
End Function
如@dotNET 所说,澄清一点。这是.net 前的代码。在 dot net 中,您可以将代码稍微更改为
Function Test() As Boolean
Dim X As Integer
X = 5
If X = 10 Then
Return True
Else
Return False
End If
End Function
这将 test
定义为 return 布尔结果的函数,您使用 Return
语句来出错。 return 结果返回到调用语句并在上述 Return
语句
处立即退出函数
例如..
Dim result As Boolean
result = test
我很好奇Exit Sub, Exit Function
,编码时是否应该避免其他?我在不同的地方读到这是一种不好的做法,如果可能的话,你应该避免它。
我在下面提供了一个函数来证明我的意思:
Function Test()
Dim X As Integer
X = 5
If X = 10 Then
Test = True
Exit Function
Else
Test = False
Exit Function
End If
End Function
In the case above, the
Exit Function
isn't necessary since the entire code will be able to finish the entire routine without an issue. But by adding it, will it cause some issues?
这取决于代码的当前上下文。如果你在一个块内(循环、Sub 或函数等)并试图离开,Exit Statement 会很好。
Return Statement will also work the same as a Exit Function
or Exit Sub
, see the answer to this SO question。但就我个人而言,当我希望 return 控制调用代码但对 return.
您使用的样式来自 VB5 和 VBA 时代,不支持 Return
语句,我们需要将 return 值直接分配给函数姓名。在 VB.NET 中,您应该始终使用 Return
赋值。 Return
将在一个语句中执行赋值和退出调用。
关于您的特定示例,我的印象是 Exit Function
语句只不过是对最近的 End Function
行执行 GoTo
。因此,您的案例中的这些语句是多余的,可能会被编译器删除(对此不确定)。
请注意,从代码可读性的角度来看,Exit
语句变成了噩梦。我最近成为这个特殊问题的受害者。 Visual Basic 是一种冗长的语言,Exit
语句不会被 reader 注意到。结构化的 If/Else
块可读性更高。
几乎在每种情况下,都有一种 "better" 方法而不是使用 Exit Function
。
以下示例将给出相同的结果,但更短,而且在我看来更清晰。
Function Test() As Boolean
Dim X As Integer
X = 5
Return (X = 10)
End Function
如@dotNET 所说,澄清一点。这是.net 前的代码。在 dot net 中,您可以将代码稍微更改为
Function Test() As Boolean
Dim X As Integer
X = 5
If X = 10 Then
Return True
Else
Return False
End If
End Function
这将 test
定义为 return 布尔结果的函数,您使用 Return
语句来出错。 return 结果返回到调用语句并在上述 Return
语句
例如..
Dim result As Boolean
result = test