天天看點

using 語句

using 語句定義一個範圍,在此範圍的末尾将處理對象。

using (expression | type identifier = initializer) statement

其中:

expression

希望在退出 using 語句時調用 Dispose 的表達式。

type

identifier 的類型。

identifier

type 類型的名稱或辨別符。定義一個以上 type 類型的 identifier 是可以的。在每一個 identifier = initializer 的前邊都有一個逗号。

initializer

建立對象的表達式。

statement

嵌入的語句或要執行的語句。

備注

在 using 語句中建立一個執行個體,確定退出 using 語句時在對象上調用 Dispose。當到達 using 語句的末尾,或者如果在語句結束之前引發異常并且控制離開語句塊,都可以退出 using 語句。

執行個體化的對象必須實作 System.IDisposable 接口。

示例

// cs_using_statement.cs

// compile with /reference:System.Drawing.dll

using System.Drawing;

class a

{

   public static void Main()

   {

      using (Font MyFont = new Font("Arial", 10.0f), MyFont2 = new Font("Arial", 10.0f))

      {

         // use MyFont and MyFont2

      }   // compiler will call Dispose on MyFont and MyFont2

      Font MyFont3 = new Font("Arial", 10.0f);

      using (MyFont3)

      {

         // use MyFont3

      }   // compiler will call Dispose on MyFont3

   }

}

繼續閱讀