如何退出 "Using" 块

How to exit from "Using" block

我正在写代码,遇到这样的情况:

Sub Example()
    Using DT As New DataTable
        '...some code
        If mCondition = True Then GoTo Other
        '...some code
    End Using
Other:
    '...some code
End Sub

我担心 "goto" 对区块的影响 "Using":它是否正常工作?

我需要使用不同的代码结构吗? (或者如果我这样做会更好)

您不必担心存在于 Using 块之外,因为一旦控制流移出块,编译器就会处理资源的处置。

来自The documentation

"A Using block behaves like a Try...Finally construction in which the Try block uses the resources and the Finally block disposes of them. Because of this, the Using block guarantees disposal of the resources, no matter how you exit the block. This is true even in the case of an unhandled exception, except for a WhosebugException."

所以你的代码实际上是这样的:

Sub Example()
    Dim DT As New DataTable
    Try
        '...some code
        If mCondition = True Then GoTo Other
        '...some code
    Finally
        DT.Dispose
    End Try
Other:
    '...some code
End Sub

话虽如此,一开始就有一个 goto 几乎总是一种代码味道,因此您可以通过某种方式进行重构。参见:GoTo statements and alternatives in VB.NET