【问题标题】:visual basic Function to return exit sub视觉基本函数返回退出子
【发布时间】:2016-05-13 14:21:29
【问题描述】:

我正在为一位朋友创建一个 Visual Basic 应用程序。无论如何,我正在尝试创建一个函数,该函数将“退出子”返回给调用该函数的子。我已经通过返回一个像 1 或 2 这样的值并在调用 sub 时插入一个 if 来解决这个问题。只是想知道是否有一个我还没有学过的返回退出子的简写。

Private Sub Button1.click() Handles Button1.Click

tryactive()

endsub    
Private Function tryactive()
        Try
            AppActivate("your aplication")
        Catch ex As Exception
            Dim msgboxresponse = MsgBox("please start your application", 0, "Can't find your application")
            If msgboxresponse = MsgBoxResult.Ok Then
                Exit Sub <------ this is the problem i want to send this back to calling sub
            End If
        End Try

    End Function

代码更大,按钮也更多。这就是为什么我要问是否有更好的方法来做到这一点。任何帮助表示赞赏。

【问题讨论】:

  • 我很确定在 VB.NET 中一个函数必须返回一个类型,否则它是一个 Sub。

标签: vb.net


【解决方案1】:

首先,您不能在 Function 中使用 Exit Sub。它应该是一个退出函数。但是根据你想要发生的事情(我猜),试试这个。

Private Sub Button1_Click() Handles Button1.Click

    If TryActive() = False Then
       Exit Sub
    End If

    'Your code you want to execute if TryActive() is True

End Sub

Private Function TryActive() as Boolean
    Try
        AppActivate("your aplication")
        Return True
    Catch ex As Exception
        Dim msgboxresponse = MsgBox("please start your application", 0, "Can't find your application")
        If msgboxresponse = MsgBoxResult.Ok Then
            Return False
        End If
    End Try
End Function

【讨论】:

  • 如果TryActive() 被标记为Function,它需要一个返回类型,可能类似于Function TryActive() As Boolean。
  • 所以我可以使用 'Sub Button1... If Not TryActive() then Exit Sub End If "rest of code if success" End Sub
  • 是的。检查我的新答案。就这样。
猜你喜欢
  • 2023-03-21
  • 1970-01-01
  • 2020-06-12
  • 1970-01-01
  • 2021-05-30
  • 1970-01-01
  • 1970-01-01
  • 2013-03-21
  • 2018-07-29
相关资源
最近更新 更多