跳過到頁腳內容
.NET幫助

C# Using(開發者的工作原理)

即使你剛開始學習 C#,你可能已經接觸過 using 指令。如果你是 IronPDF 用戶,你會非常熟悉以命名空間 using ironpdf 開始你的程式碼。

然而,using 關鍵字還有另一種用途。 在本指南中,我們將探討 using statement - 它是什麼、如何運作,以及如何幫助您建立更有效率的程式碼。 讓我們深入瞭解!

什麼是 C# 使用?

C# 中的 using 語句是使用實作 IDisposable 介面的資源的方便方法。 IDisposable 物件通常會保留未經管理的資源,例如檔案句柄或網路連線,當您使用完畢後需要釋放這些資源。 這就是使用說明發揮作用的地方 - 它可以幫助您確保這些資源在使用後得到妥善的處理。

Using 語句如何運作

當您使用 using 語句時,C# 會在不再需要物件時,自動呼叫物件上的 Dispose 方法。 這表示您不必手動呼叫 Dispose 方法或擔心忘記呼叫。 使用說明會幫您搞定這一點!

讓我們來看看一個簡單的範例,看看 using statement 在實際應用中是如何運作的:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        // Using a using statement to ensure StreamReader is disposed of
        using (StreamReader reader = new StreamReader("example.txt"))
        {
            string content = reader.ReadToEnd();
            Console.WriteLine(content);
        }
    }
}
using System;
using System.IO;

class Program
{
    static void Main()
    {
        // Using a using statement to ensure StreamReader is disposed of
        using (StreamReader reader = new StreamReader("example.txt"))
        {
            string content = reader.ReadToEnd();
            Console.WriteLine(content);
        }
    }
}
Imports System
Imports System.IO

Friend Class Program
	Shared Sub Main()
		' Using a using statement to ensure StreamReader is disposed of
		Using reader As New StreamReader("example.txt")
			Dim content As String = reader.ReadToEnd()
			Console.WriteLine(content)
		End Using
	End Sub
End Class
$vbLabelText   $csharpLabel

在這個範例中,名為 reader 的 StreamReader 物件包裝在一個 using 區塊中。 當 using 區塊退出時,讀取器會自動呼叫 Dispose 方法,釋放它所保留的任何資源。

使用區塊 vs. 使用宣告。

從 C# 8.0 開始,您可以使用 using 宣告來取代 using 區塊。 using 聲明是定義一次性物件的一種更短更簡潔的方式,就像這樣:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        // Using the using declaration simplifies the code
        using var reader = new StreamReader("example.txt");
        string content = reader.ReadToEnd();
        Console.WriteLine(content);
    }
}
using System;
using System.IO;

class Program
{
    static void Main()
    {
        // Using the using declaration simplifies the code
        using var reader = new StreamReader("example.txt");
        string content = reader.ReadToEnd();
        Console.WriteLine(content);
    }
}
Imports System
Imports System.IO

Friend Class Program
	Shared Sub Main()
		' Using the using declaration simplifies the code
		Dim reader = New StreamReader("example.txt")
		Dim content As String = reader.ReadToEnd()
		Console.WriteLine(content)
	End Sub
End Class
$vbLabelText   $csharpLabel

有了 using 聲明,您就不需要大括號或縮排,讓您的程式碼更具可讀性。 當變數離開範圍時,仍會自動呼叫 Dispose 方法。

Try 區塊、Finally 區塊和 Using 語句。

您可能想知道 using 語句與 C# 中的 try 和 finally 區塊有何關聯。 那麼,using 語句實際上是 try-finally 區塊的縮寫!

以下是與之前相同的範例,但在撰寫時使用 try-finally 區塊而非 using 語句:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        StreamReader reader = null;
        try
        {
            reader = new StreamReader("example.txt");
            string content = reader.ReadToEnd();
            Console.WriteLine(content);
        }
        finally
        {
            if (reader != null)
            {
                reader.Dispose();
            }
        }
    }
}
using System;
using System.IO;

class Program
{
    static void Main()
    {
        StreamReader reader = null;
        try
        {
            reader = new StreamReader("example.txt");
            string content = reader.ReadToEnd();
            Console.WriteLine(content);
        }
        finally
        {
            if (reader != null)
            {
                reader.Dispose();
            }
        }
    }
}
Imports System
Imports System.IO

Module Program
    Sub Main()
        Dim reader As StreamReader = Nothing
        Try
            reader = New StreamReader("example.txt")
            Dim content As String = reader.ReadToEnd()
            Console.WriteLine(content)
        Finally
            If reader IsNot Nothing Then
                reader.Dispose()
            End If
        End Try
    End Sub
End Module
$vbLabelText   $csharpLabel

正如您所看到的,using 語句移除了 try-finally 區塊和對 Dispose 方法的明確呼叫,使代碼更乾淨、更易讀。

管理多種資源

using statement 的一大優點是可以同時處理多種資源。 您可以一個接一個堆疊 using 語句,或使用單一 using 語句來處理逗號分隔清單中的多個資源。下面的範例展示了這兩種方法:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        // Stacking using statements for multiple disposable resources
        using (StreamReader reader1 = new StreamReader("example1.txt"))
        using (StreamReader reader2 = new StreamReader("example2.txt"))
        {
            string content1 = reader1.ReadToEnd();
            string content2 = reader2.ReadToEnd();
            Console.WriteLine($"Content from example1.txt:\n{content1}\nContent from example2.txt:\n{content2}");
        }

        // Attempting to use a single using statement with multiple resources (not valid)
        // Note: This method using comma-separated resources is not supported in C#
    }
}
using System;
using System.IO;

class Program
{
    static void Main()
    {
        // Stacking using statements for multiple disposable resources
        using (StreamReader reader1 = new StreamReader("example1.txt"))
        using (StreamReader reader2 = new StreamReader("example2.txt"))
        {
            string content1 = reader1.ReadToEnd();
            string content2 = reader2.ReadToEnd();
            Console.WriteLine($"Content from example1.txt:\n{content1}\nContent from example2.txt:\n{content2}");
        }

        // Attempting to use a single using statement with multiple resources (not valid)
        // Note: This method using comma-separated resources is not supported in C#
    }
}
Imports Microsoft.VisualBasic
Imports System
Imports System.IO

Friend Class Program
	Shared Sub Main()
		' Stacking using statements for multiple disposable resources
		Using reader1 As New StreamReader("example1.txt")
		Using reader2 As New StreamReader("example2.txt")
			Dim content1 As String = reader1.ReadToEnd()
			Dim content2 As String = reader2.ReadToEnd()
			Console.WriteLine($"Content from example1.txt:" & vbLf & "{content1}" & vbLf & "Content from example2.txt:" & vbLf & "{content2}")
		End Using
		End Using

		' Attempting to use a single using statement with multiple resources (not valid)
		' Note: This method using comma-separated resources is not supported in C#
	End Sub
End Class
$vbLabelText   $csharpLabel

注意:C# 不支援單一 using 語句包含多個以逗號分隔的資源。 每個資源都需要有自己的使用說明。

實作 IDisposable 介面

有時候,您可能會建立自己的自訂類別來管理一個或多個資源。 如果您的類別負責處理一次性物件或非管理資源,您應該實作 IDisposable 介面。

以下是一個實作 IDisposable 介面的自訂類別範例:

using System;
using System.IO;

public class CustomResource : IDisposable
{
    private StreamReader _reader;

    public CustomResource(string filePath)
    {
        _reader = new StreamReader(filePath);
    }

    public void ReadContent()
    {
        string content = _reader.ReadToEnd();
        Console.WriteLine(content);
    }

    public void Dispose()
    {
        if (_reader != null)
        {
            _reader.Dispose();
            _reader = null;
        }
    }
}
using System;
using System.IO;

public class CustomResource : IDisposable
{
    private StreamReader _reader;

    public CustomResource(string filePath)
    {
        _reader = new StreamReader(filePath);
    }

    public void ReadContent()
    {
        string content = _reader.ReadToEnd();
        Console.WriteLine(content);
    }

    public void Dispose()
    {
        if (_reader != null)
        {
            _reader.Dispose();
            _reader = null;
        }
    }
}
Imports System
Imports System.IO

Public Class CustomResource
	Implements IDisposable

	Private _reader As StreamReader

	Public Sub New(ByVal filePath As String)
		_reader = New StreamReader(filePath)
	End Sub

	Public Sub ReadContent()
		Dim content As String = _reader.ReadToEnd()
		Console.WriteLine(content)
	End Sub

	Public Sub Dispose() Implements IDisposable.Dispose
		If _reader IsNot Nothing Then
			_reader.Dispose()
			_reader = Nothing
		End If
	End Sub
End Class
$vbLabelText   $csharpLabel

在這個範例中,CustomResource 類別管理一個 StreamReader 物件,這是一個一次性的物件。 透過實作 IDisposable 介面並實作 Dispose 方法,我們可以對這個類別的實體使用 using 語句。

以下是您如何在 CustomResource 類中使用 using 語句:

class Program
{
    static void Main()
    {
        using (CustomResource resource = new CustomResource("example.txt"))
        {
            resource.ReadContent();
        }
    }
}
class Program
{
    static void Main()
    {
        using (CustomResource resource = new CustomResource("example.txt"))
        {
            resource.ReadContent();
        }
    }
}
Friend Class Program
	Shared Sub Main()
		Using resource As New CustomResource("example.txt")
			resource.ReadContent()
		End Using
	End Sub
End Class
$vbLabelText   $csharpLabel

當 using 區塊結束時,Dispose 方法將會被呼叫,處置它所管理的 StreamReader 物件。

使用 Using 語句處理異常。

using statement 的另一個好處是有助於更優雅地處理異常。 如果在 using 區塊中發生異常,仍會在資源上呼叫 Dispose 方法,以確保適當的清理。

例如,請考慮以下程式碼:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        try
        {
            using (StreamReader reader = new StreamReader("nonexistentfile.txt"))
            {
                string content = reader.ReadToEnd();
                Console.WriteLine(content);
            }
        }
        catch (FileNotFoundException ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}
using System;
using System.IO;

class Program
{
    static void Main()
    {
        try
        {
            using (StreamReader reader = new StreamReader("nonexistentfile.txt"))
            {
                string content = reader.ReadToEnd();
                Console.WriteLine(content);
            }
        }
        catch (FileNotFoundException ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}
Imports System
Imports System.IO

Friend Class Program
	Shared Sub Main()
		Try
			Using reader As New StreamReader("nonexistentfile.txt")
				Dim content As String = reader.ReadToEnd()
				Console.WriteLine(content)
			End Using
		Catch ex As FileNotFoundException
			Console.WriteLine($"Error: {ex.Message}")
		End Try
	End Sub
End Class
$vbLabelText   $csharpLabel

在這種情況下,如果程式碼發生 FileNotFoundException,該異常會被 catch 區塊捕獲並處理。 即使異常發生在 using 區塊中,仍會在 StreamReader 物件上呼叫 Dispose 方法,以確保沒有資源外洩。

使用 IronPDF 和 Using Statement

IronPDF 是一種常用的函式庫,用於在 C# 和 .NET 應用程式中建立、編輯和提取 PDF 檔案。 與其他使用資源的函式庫一樣,IronPDF 也可以從 using statement 中獲益,以確保資源管理得宜。

讓我們來探討如何在 IronPDF 中使用 using 語句,從 HTML 字串建立 PDF 文件,展現 using 語句在實際情境中的威力。

首先,確保您已在專案中安裝 IronPDF NuGet 套件:

Install-Package IronPdf

現在,讓我們從 PDF 檔案中擷取所有資料:

using IronPdf;

class Program
{
    static void Main()
    {
        // Using a using statement with IronPDF to ensure resources are managed
        using (PdfDocument pdfDocument = PdfDocument.FromFile("PDFData.pdf"))
        {
            string extractedText = pdfDocument.ExtractAllText();
            Console.WriteLine(extractedText);
        }
    }
}
using IronPdf;

class Program
{
    static void Main()
    {
        // Using a using statement with IronPDF to ensure resources are managed
        using (PdfDocument pdfDocument = PdfDocument.FromFile("PDFData.pdf"))
        {
            string extractedText = pdfDocument.ExtractAllText();
            Console.WriteLine(extractedText);
        }
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main()
		' Using a using statement with IronPDF to ensure resources are managed
		Using pdfDocument As PdfDocument = PdfDocument.FromFile("PDFData.pdf")
			Dim extractedText As String = pdfDocument.ExtractAllText()
			Console.WriteLine(extractedText)
		End Using
	End Sub
End Class
$vbLabelText   $csharpLabel

在這段程式碼中,我們使用 PdfDocument.FromFile 方法開啟名為"PDFData.pdf"的 PDF 檔案。 這個方法會返回一個 PdfDocument 範例,我們將它包裝在一個 using 語句中。

在 using 程式碼區塊中,我們呼叫 PdfDocument 實例上的 ExtractAllText 來擷取 PDF 中的所有文字。 當 using 區塊退出時,Dispose 方法會自動在 PdfDocument 上呼叫,釋放它所持有的任何資源。

透過在 PdfDocument 中使用 using 語句,我們可以確保在完成從 PDF 檔案中擷取文字之後,即使在過程中發生異常,也能正確關閉 PDF 檔案。 這是一個很好的例子,說明 using 語句如何在 C# 中協助有效管理資源。

!a href="/static-assets/pdf/blog/csharp-using/csharp-using-1.webp">C# Using Statement

包裝。

以上就是使用說明的簡介! 我們已經看到它如何確保有效處理一次性物件,無縫管理一個或多個資源。 using statement 不僅有助於保持程式碼的整潔,還能增強 C# 專案的可讀性。

我們還介紹了 IronPDF,這是一個用於在 C# 中操作 PDF 的強大程式庫。 結合 IronPDF 使用 using statement 展示此代碼功能的實際應用,強化概念及其重要性。

準備好使用 IronPDF 了嗎? 您可以從我們的 30天免費試用 IronPDF 和 Iron Software's Suite 開始。 它還可以完全免費用於開發目的,讓您真正能一窺其真面目。 如果您喜歡您所看到的,IronPDF 的許可選項起價低至 $999 。 若想節省更多的費用,請查看 Iron Suite 完整軟體套件,您可以用兩個套件的價格獲得全部九個 Iron Software 工具。 祝您編碼愉快!

IronPDF 使用說明

常見問題解答

C# 中的 using 語句的目的是什麼?

C# 中的 using 語句用於管理實作 IDisposable 介面的資源,例如檔案控制項或網路連接,確保它們在使用後被正確釋放。

C# 中的 using 語句如何幫助防止資源洩漏?

using 語句會自動在物件不再需要時呼叫 Dispose 方法,這有助於確保即使發生異常,也能釋放資源,從而防止資源洩漏。

C# 中的 using 區塊與 using 宣告有何不同?

使用區塊將代碼包裹在大括號中,並確保在區塊結束時處理,而使用宣告(在 C# 8.0 中引入)更簡潔,並在作用域結束時自動釋放資源。

如何在我的自訂 C# 類別中實作 IDisposable?

要在自訂類別中實作 IDisposable,需要定義一個 Dispose 方法來釋放非受控資源,允許使用 using 語句進行自動資源管理。

C# 中的 using 語句能處理多個資源嗎?

是的,你可以連續使用多個 using 語句來管理多個資源,儘管不支持使用單個 using 語句和逗號分隔的多個資源。

為什麼 C# 中的 using 語句優於 try-finally 區塊?

using 語句因其更簡潔的語法和自動資源管理而被優先使用,這相較於手動實現 try-finally 區塊來確保資源釋放大大簡化了代碼。

如何在 C# 中有效管理 PDF 文件?

可以使用 IronPDF 有效管理 PDF 文件,它與 using 語句整合以確保資源(如文件實例)在執行文字提取等操作後被正確關閉。

是否有用於 C# 開發的 PDF 庫試用版可用?

是的,某些 PDF 庫提供30天免費試用版,並且可免費用於開發用途,讓您在購買前探索其功能。

Jacob Mellor, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我