vb.net - 什么时候可以在 VB.Net 中使用 GoTo 语句?

标签 vb.net goto

我有一个流程需要在数据库中创建一堆记录,并在出现问题时回滚所有内容。我想做的是这样的:

Public Structure Result
    Public Success as Boolean
    Public Message as String
End Structure

Private _Repository as IEntityRepository

Public Function SaveOrganization( _
    ByVal organization As rv_o_Organization) As Result
    Dim result = Result.Empty

    _Repository.Connection.Open()
    _Repository.Transaction = _Repository.Connection.BeginTransaction()

    ''//Performs validation then saves it to the database
    ''// using the current transaction
    result = SaveMasterOrganization(organization.MasterOrganization)
    If (Not result.Success) Then
        GoTo somethingBadHappenedButNotAnException
    End If

    ''//Performs validation then saves it to the database
    ''//using the current transaction
    result = SaveOrganziation(dbOrg, organization)
    If (Not result.Success) Then GoTo somethingBadHappenedButNotAnException

somethingBadHappenedButNotAnException:
    _Repository.Transaction.Commit()
    _Repository.Connection.Close()
    Return result
End Sub

这是 GoTo 语句的正确使用,还是只是非常糟糕的设计?有更优雅的解决方案吗?希望这个示例能够阐明要点

最佳答案

如果你必须问,就不要问。

对于您的特定代码,您可以这样做:

Public Function SaveOrganization(ByVal organization As rv_o_Organization) As Result
    Dim result As Result = Result.Empty

    _Repository.Connection.Open()
    _Repository.Transaction = _Repository.Connection.BeginTransaction()

    'Performs validation then saves it to the database 
    'using the current transaction
    result = SaveMasterOrganization(organization.MasterOrganization)

    'Performs validation then saves it to the database 
    'using the current transaction
    If result.Success Then result = SaveOrganziation(dbOrg, organization)

    _Repository.Transaction.Commit()
    _Repository.Connection.Close()
    Return result
End Sub

关于vb.net - 什么时候可以在 VB.Net 中使用 GoTo 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/567386/

相关文章:

sql - 在sql server中使用不同的过滤器选择数据

javascript - 为什么这个从 VB.NET 移植的 JavaScript 没有执行?

asp.net - WindowsAzure.Storage 生产中出现 403 错误

javascript - 如果提取的 TXT 不包含某个单词,我如何告诉 imacros 转到某个 url?

.net - 有没有办法在没有 GoTo 语句的情况下写这个?

ruby-on-rails - Ruby on Rails : Best way to handle repeated error checking without goto?

vb.net - 如何设置基本的 VB.NET WinForms 应用程序

mysql - 从dest_table插入src_表,不重复

c++ - goto语句与递归

javascript - 在没有额外标志的情况下解决 JavaScript 缺少 goto 的问题