Using 陳述式 (Visual Basic)Using Statement (Visual Basic)

宣告的開頭Using封鎖,並選擇性地取得區塊所控制的系統資源。Declares the beginning of a Using block and optionally acquires the system resources that the block controls.


Using { resourcelist | resourceexpression }  
    [ statements ]  
End Using  


詞彙Term 定義Definition
resourcelist 如果您未提供所需resourceexpressionRequired if you do not supply resourceexpression. 這個清單的一或多個系統資源Using封鎖控制項,並以逗號分隔。List of one or more system resources that this Using block controls, separated by commas.
resourceexpression 如果您未提供所需resourcelistRequired if you do not supply resourcelist. 參考變數或運算式,指的系統資源,來控制這個Using區塊。Reference variable or expression referring to a system resource to be controlled by this Using block.
statements 選擇性。Optional. 陳述式區塊,Using封鎖執行。Block of statements that the Using block runs.
End Using 必要項。Required. 結束的定義Using區塊,並處置它所控制的所有資源。Terminates the definition of the Using block and disposes of all the resources that it controls.

在每個資源resourcelist組件具有下列語法和組成部分:Each resource in the resourcelist part has the following syntax and parts:

resourcename As New resourcetype [ ( [ arglist ] ) ]


resourcename As resourcetype = resourceexpression

resourcelist 組件resourcelist Parts

詞彙Term 定義Definition
resourcename 必要項。Required. 指的是系統資源的參考變數,Using封鎖控制權。Reference variable that refers to a system resource that the Using block controls.
New 需要Using陳述式會取得資源。Required if the Using statement acquires the resource. 如果您已經取得資源,請使用第二個語法替代方案。If you have already acquired the resource, use the second syntax alternative.
resourcetype 必要項。Required. 資源的類別。The class of the resource. 此類別必須實作IDisposable介面。The class must implement the IDisposable interface.
arglist 選擇性。Optional. 您要傳遞至要建立的執行個體建構函式的引數清單的resourcetypeList of arguments you are passing to the constructor to create an instance of resourcetype. 請參閱參數清單See Parameter List.
resourceexpression 必要項。Required. 變數或運算式指滿足需求的系統資源resourcetypeVariable or expression referring to a system resource satisfying the requirements of resourcetype. 如果您使用第二個語法替代方案,您必須先取得資源,將控制項傳遞至Using陳述式。If you use the second syntax alternative, you must acquire the resource before passing control to the Using statement.


有時候您的程式碼需要 unmanaged 的資源,例如檔案控制代碼、 COM 包裝函式或 SQL 連接。Sometimes your code requires an unmanaged resource, such as a file handle, a COM wrapper, or a SQL connection. AUsing區塊與他們完成您的程式碼時,保證一或多個這類資源的處置。A Using block guarantees the disposal of one or more such resources when your code is finished with them. 這使其可供其他程式碼使用。This makes them available for other code to use.

受管理的資源處置掉.NET Framework 記憶體回收行程 (GC) 而不需要任何額外的程式碼,就在您的組件。Managed resources are disposed of by the .NET Framework garbage collector (GC) without any extra coding on your part. 您不需要Using區塊的 managed 資源。You do not need a Using block for managed resources. 不過,您仍然可以使用Using區塊,以強制受管理的資源,而不是等待記憶體回收行程的處置。However, you can still use a Using block to force the disposal of a managed resource instead of waiting for the garbage collector.

AUsing區塊有三個部分︰ 取得、 使用量以及各種可供使用。A Using block has three parts: acquisition, usage, and disposal.

  • 取得表示建立變數,並初始化參考的系統資源。Acquisition means creating a variable and initializing it to refer to the system resource. Using陳述式可以取得一或多個資源,或您可以輸入區塊之前,先取得一個資源,並提供它Using陳述式。The Using statement can acquire one or more resources, or you can acquire exactly one resource before entering the block and supply it to the Using statement. 如果您提供resourceexpression,您必須先取得資源,將控制項傳遞至Using陳述式。If you supply resourceexpression, you must acquire the resource before passing control to the Using statement.

  • 使用量表示的資源存取和使用它們執行動作。Usage means accessing the resources and performing actions with them. 之間的陳述式UsingEnd Using代表資源的使用量。The statements between Using and End Using represent the usage of the resources.

  • 處置方法呼叫Dispose方法中的物件上resourcenameDisposal means calling the Dispose method on the object in resourcename. 這可讓物件完全終止其資源。This allows the object to cleanly terminate its resources. End Using陳述式處置的資源下Using區塊的控制項。The End Using statement disposes of the resources under the Using block's control.


AUsing區塊的行為類似Try...Finally所在的建構Try區塊中使用的資源和Finally區塊處置它們。A Using block behaves like a Try...Finally construction in which the Try block uses the resources and the Finally block disposes of them. 因為這個緣故,Using區塊都保證會處置的資源,無論您如何結束區塊。Because of this, the Using block guarantees disposal of the resources, no matter how you exit the block. 即使發生例外狀況,則為 true,這是除了StackOverflowExceptionThis is true even in the case of an unhandled exception, except for a StackOverflowException.

取得每個資源變數的範圍Using陳述式僅限於Using區塊。The scope of every resource variable acquired by the Using statement is limited to the Using block.

如果您指定一個以上的系統資源,在Using陳述式,效果會相同,如同您巢狀Using封鎖其中一個在另一個。If you specify more than one system resource in the Using statement, the effect is the same as if you nested Using blocks one within another.

如果resourcenameNothing,不需要呼叫Dispose進行,而且會擲回任何例外狀況。If resourcename is Nothing, no call to Dispose is made, and no exception is thrown.

處理使用的區塊內的結構化例外狀況Structured Exception Handling Within a Using Block

如果您需要處理中可能發生的例外狀況Using區塊中,您可以新增完整Try...Finally給它的建構。If you need to handle an exception that might occur within the Using block, you can add a complete Try...Finally construction to it. 如果您要處理的情況所在Using陳述式不成功取得資源,您可以測試是否resourcenameNothingIf you need to handle the case where the Using statement is not successful in acquiring a resource, you can test to see if resourcename is Nothing.

結構化例外狀況,而不使用區塊處理Structured Exception Handling Instead of a Using Block

如果您需要更精細地控制擷取的資源,或您需要額外的程式碼中Finally區塊中,您可以重新撰寫Using封鎖Try...Finally建構。If you need finer control over the acquisition of the resources, or you need additional code in the Finally block, you can rewrite the Using block as a Try...Finally construction. 下列範例示範基本架構TryUsing建構,而且相當於取得和處置resourceThe following example shows skeleton Try and Using constructions that are equivalent in the acquisition and disposal of resource.

Using resource As New resourceType   
    ' Insert code to work with resource.  
End Using  
' For the acquisition and disposal of resource, the following  
' Try construction is equivalent to the Using block.  
Dim resource As New resourceType  
    ' Insert code to work with resource.  
    If resource IsNot Nothing Then  
    End If  
End Try   


內的程式碼Using區塊不應該指派中的物件resourcename給另一個變數。The code inside the Using block should not assign the object in resourcename to another variable. 當您結束Using區塊中,資源處置,而另一個變數無法存取它所指向的資源。When you exit the Using block, the resource is disposed, and the other variable cannot access the resource to which it points.


下列範例會建立名為 log.txt,並將兩行文字寫入檔案的檔案。The following example creates a file that is named log.txt and writes two lines of text to the file. 範例也會讀取該相同的檔案,並顯示的文字行。The example also reads that same file and displays the lines of text.

因為TextWriterTextReader類別會實作IDisposable介面,可以使用程式碼Using陳述式來確認檔案正確關閉之後寫入和讀取作業。Because the TextWriter and TextReader classes implement the IDisposable interface, the code can use Using statements to ensure that the file is correctly closed after the write and read operations.

Private Sub WriteFile()
    Using writer As System.IO.TextWriter = System.IO.File.CreateText("log.txt")
        writer.WriteLine("This is line one.")
        writer.WriteLine("This is line two.")
    End Using
End Sub

Private Sub ReadFile()
    Using reader As System.IO.TextReader = System.IO.File.OpenText("log.txt")
        Dim line As String

        line = reader.ReadLine()
        Do Until line Is Nothing
            line = reader.ReadLine()
    End Using
End Sub

另請參閱See also