C# using

來源:互聯網
上載者:User

using 關鍵字有兩個主要用途:

  • 作為指令,用於為命名空間建立別名或匯入其他命名空間中定義的類型。  
  • 作為語句,用於定義一個範圍,在此範圍的末尾將釋放對象。

 

*作為指令

  using 指令有兩個用途:

  • 允許在命名空間中使用類型,這樣,您就不必在該命名空間中限定某個類型的使用:

 

using System.Text;

 

  • 為命名空間或類型建立別名。

 

using Project = PC.MyCompany.Project;

 

 

 

*作為語句

    定義一個範圍,將在此範圍之外釋放一個或多個對象。

 

using (Font font1 = new Font("Arial", 10.0f))
{
}

 

 

  C# 通過 .NET Framework 公用語言運行庫 (CLR) 自動釋放用於儲存不再需要的對象的記憶體。記憶體的釋放具有不確定性;一旦 CLR 決定執行記憶體回收,就會釋放記憶體。但是,通常最好儘快釋放諸如檔案控制代碼和網路連接這樣的有限資源。

  using 語句允許程式員指定使用資源的對象應當何時釋放資源。為 using 語句提供的對象必須實現 IDisposable 介面。此介面提供了 Dispose 方法,該方法將釋放此對象的資源。

  可以在到達 using 語句的末尾時,或者在該語句結束之前引發了異常並且控制權離開語句塊時,退出 using 語句。

  可以在 using 語句中聲明對象(如上所示),或者在 using 語句之前聲明對象,如下所示:

 

Font font2 = new Font("Arial", 10.0f);
using (font2)
{
// use font2
}

 

可以有多個對象與 using 語句一起使用,但是必須在 using 語句內部聲明這些對象,如下所示:

 

 

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

 

 

樣本:

  下面的樣本顯示使用者定義類可以如何?它自己的 Dispose 行為。注意類型必須從 IDisposable 繼承。

 

using System;

class C : IDisposable
{
public void UseLimitedResource()
{
Console.WriteLine("Using limited resource...");
}

void IDisposable.Dispose()
{
Console.WriteLine("Disposing limited resource.");
}
}

class Program
{
static void Main()
{
using (C c = new C())
{
c.UseLimitedResource();
}
Console.WriteLine("Now outside using statement.");
Console.ReadLine();
}
}

 

using語句的本質

使用using語句實際上產生的IL代碼中是一個try, finally代碼塊,在finally代碼塊裡釋放資源。

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.