跳過到頁腳內容
.NET幫助

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

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

但是,"using"關鍵字還有另一種用途。 在本指南中,我們將了解 using 語句——它是什麼,它是如何運作的,以及它如何幫助您創建更有效率的程式碼。 讓我們開始吧!

C# 中的 Using 是什麼?

C# 中的 using 語句是使用實作了 IDisposable 介面的資源的便捷方式。 IDisposable 物件通常會持有非託管資源,例如檔案句柄或網路連接,這些資源在使用完畢後需要釋放。 這時 using 語句就派上用場了——它可以幫助確保這些資源在使用後得到妥善處置。

using 語句的工作原理

使用 using 語句時,C# 會在不再需要物件時自動呼叫 Dispose 方法。 這意味著您無需手動呼叫 Dispose 方法,也不用擔心忘記呼叫。 using 語句會自動處理這個問題!

讓我們來看一個簡單的例子,了解 using 語句在實際應用上是如何運作的:

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);
        }
    }
}
$vbLabelText   $csharpLabel

在這個範例中,名為 reader 的 StreamReader 物件被包裝在一個 using 區塊中。 當 using 程式碼區塊退出時,會自動呼叫 reader 的 Dispose 方法,釋放它所佔用的所有資源。

使用程式碼區塊與使用聲明

從 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);
    }
}
$vbLabelText   $csharpLabel

使用 using 聲明後,就不需要花括號或縮進,讓程式碼更易讀。 即使變數超出作用域,Dispose 方法仍然會自動呼叫。

try 程式碼區塊、finally 程式碼區塊和 using 語句

你可能想知道 C# 中的 using 語句與 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\static-assets\pdf\blog\csharp-using\csharp-using-2.webp
        {
            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\static-assets\pdf\blog\csharp-using\csharp-using-2.webp
        {
            if (reader != null)
            {
                reader.Dispose();
            }
        }
    }
}
$vbLabelText   $csharpLabel

如您所見,using 語句消除了 try-finally 區塊和對 Dispose 方法的明確調用,使程式碼更簡潔易讀。

管理多種資源

using 語句的一大優點是它可以同時處理多個資源。 你可以將 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#
    }
}
$vbLabelText   $csharpLabel

注意:C# 不支援在單一 using 語句中使用逗號分隔多個資源。 每個資源都需要自己的 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;
        }
    }
}
$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();
        }
    }
}
$vbLabelText   $csharpLabel

當 using 程式碼區塊終止時,將呼叫 Dispose 方法,釋放它所管理的 StreamReader 物件。

使用 using 語句處理異常

using 語句的另一個好處是,它有助於更優雅地處理異常。 如果 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}");
        }
    }
}
$vbLabelText   $csharpLabel

在這種情況下,如果程式碼拋出 FileNotFoundException 異常,則該異常會被 catch 區塊捕獲並處理。 即使異常發生在 using 程式碼區塊內,StreamReader 物件仍然會呼叫 Dispose 方法,從而確保不會發生資源洩漏。

使用IronPDF和 Using 語句

IronPDF是一個流行的庫,用於在 C# 和.NET應用程式中建立、編輯和提取 PDF 文件。 與其他使用資源的函式庫一樣, IronPDF也可以透過 using 語句來確保正確的資源管理。

讓我們來探討如何使用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);
        }
    }
}
$vbLabelText   $csharpLabel

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

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

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

C# 使用語句

總結

以上就是 using 語句的簡介! 我們已經看到它如何確保高效處理一次性物品,無縫管理一種或多種資源。 using 語句不僅有助於保持程式碼更簡潔,還能提升 C# 專案的可讀性。

我們還推出了IronPDF,這是一個功能強大的 C# PDF 操作庫。 將 using 語句與IronPDF結合使用,可以示範此程式碼特性的實際應用,從而強化此概念及其重要性。

準備好體驗IronPDF了嗎? 您可以先體驗IronPDF和 Iron Software 套件的 30 天免費試用版。 它也完全可以免費用於開發目的,因此您可以真正了解它的功能。 如果您喜歡您所看到的, IronPDF 的許可選項起價低至 $799 。 想要節省更多?那就來看看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技術的創新,同時指導下一代技術領導者。

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me