【问题标题】:Best practice to exit sub with functions使用函数退出子的最佳实践
【发布时间】:2018-07-31 15:02:31
【问题描述】:

我正在寻找一种方法来编写一个可以停止所有代码(退出子)的函数,而无需为子例程中的函数编写 If 语句

例如:

Public Class Form_Main
    Private Sub Button_Search_Click(sender As Object, e As EventArgs) Handles Button_Search.Click
        If CountNumbers() = False Then Exit Sub 
        ' Is there a way for me to write "CountNumbers" only and it will
        ' [Exit Sub] without me having to write an if statement?
        ' Sort of embedding the Exit Sub in the function?
    End Sub

    Function CountNumbers()
        Dim a As Integer = 1
        If a = 1 Then
            Return False
        End If
        Return True
    End Function

End Class

【问题讨论】:

  • 不,没有。你为什么要这样做呢?内联 If 语句有什么问题?
  • “If 语句”有什么问题?
  • 这将为您带来什么?它会使代码不可读,尤其是对于下一个不知道代码正在从该行退出的程序员。
  • 如果您正在寻找最佳实践,请从 Option Strict 开始
  • 是的,只需调用 CountNumbers(),因为您没有对 CountNumbers 的结果做任何事情,无论如何 sub 都会退出。如果您从不退出点击处理程序,您的应用程序将永远挂起。

标签: vb.net winforms function return


【解决方案1】:

您使用 Return 关键字而不提供值

Public Sub Foo()
    If Bar() = False Then
        Return
    End If
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多