using 陳述式 (C# 參考)using statement (C# Reference)

提供方便的語法,以確保正確使用 IDisposable 物件。Provides a convenient syntax that ensures the correct use of IDisposable objects.

範例Example

下列範例顯示如何使用 using 陳述式。The following example shows how to use the using statement.

using (var font1 = new Font("Arial", 10.0f)) 
{
    byte charset = font1.GdiCharSet;
}

備註Remarks

FileFont 是 Managed 類型的範例,這些類型會存取 Unmanaged 資源 (在本例中為檔案控制代碼和裝置內容)。File and Font are examples of managed types that access unmanaged resources (in this case file handles and device contexts). 還有許多其他類型的 Unmanaged 資源,以及封裝這些資源的類別庫類型。There are many other kinds of unmanaged resources and class library types that encapsulate them. 所有這些類型都會實作 IDisposable 介面。All such types must implement the IDisposable interface.

IDisposable 物件的存留期限制為單一方法時,您應該在 using 陳述式中宣告它並加以具現化。When the lifetime of an IDisposable object is limited to a single method, you should declare and instantiate it in the using statement. using 陳述式會以正確的方式呼叫物件上的 Dispose 方法,而且 (當您如稍早所示使用它時) 它也會在一呼叫 Dispose 時讓物件本身超出範圍。The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. using 區塊內,物件是唯讀的,而且無法加以修改或重新指派。Within the using block, the object is read-only and cannot be modified or reassigned.

using 陳述式可確保會呼叫 Dispose,即使在 using 區塊內發生例外狀況也一樣。The using statement ensures that Dispose is called even if an exception occurs within the using block. 您可以將物件放在 try 區塊內,然後在 finally 區塊中呼叫 Dispose,來達到相同的結果;事實上,這就是編譯器轉譯 using 陳述式的方式。You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler. 稍早的程式碼範例會在編譯時期展開為下列程式碼 (注意額外的大括號是為了建立物件的有限範圍):The code example earlier expands to the following code at compile time (note the extra curly braces to create the limited scope for the object):

{
  var font1 = new Font("Arial", 10.0f);
  try
  {
    byte charset = font1.GdiCharSet;
  }
  finally
  {
    if (font1 != null)
      ((IDisposable)font1).Dispose();
  }
}

如需 try-finally 陳述式的詳細資訊,請參閱 try-finally 主題。For more information about the try-finally statement, see the try-finally topic.

您可以在 using 陳述式中宣告一種類型的多個執行個體,如下列範例所示:Multiple instances of a type can be declared in the using statement, as shown in the following example:

using (var font3 = new Font("Arial", 10.0f),
            font4 = new Font("Arial", 10.0f))
{
    // Use font3 and font4.
}

您可以具現化資源物件,然後將變數傳遞至 using 陳述式,但這不是最佳做法。You can instantiate the resource object and then pass the variable to the using statement, but this is not a best practice. 在此情況下,控制權離開 using 區塊之後,物件仍會留在範圍內,不過它可能無法再存取其非受控資源。In this case, after control leaves the using block, the object remains in scope but probably has no access to its unmanaged resources. 換句話說,它不再是完全初始化。In other words, it's not fully initialized anymore. 如果您嘗試在 using 區塊外部使用該物件,則會有導致擲回例外狀況的風險。If you try to use the object outside the using block, you risk causing an exception to be thrown. 因此,通常最好在 using 陳述式中具現化物件,並將其範圍限制為 using 區塊。For this reason, it's generally better to instantiate the object in the using statement and limit its scope to the using block.

var font2 = new Font("Arial", 10.0f);
using (font2) // not recommended
{
    // use font2
}
// font2 is still in scope
// but the method call throws an exception
float f = font2.GetHeight();

如需處置 IDisposable 物件的詳細資訊,請參閱使用實作 IDisposable 的物件For more information about disposing of IDisposable objects, see Using objects that implement IDisposable.

C# 語言規格C# language specification

如需詳細資訊,請參閱 C# 語言規格中的 using 陳述式For more information, see The using statement in the C# Language Specification. 語言規格是 C# 語法及用法的限定來源。The language specification is the definitive source for C# syntax and usage.

另請參閱See also