跳過到頁腳內容
.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);
        }
    }
}
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塊退出時,會自動對reader調用Dispose方法,釋放它所擁有的任何資源。

Using塊VS. using聲明

從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方法仍然會被自動調用。

嘗試塊,最終塊和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\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();
            }
        }
    }
}
Imports System
Imports System.IO

Friend Class Program
	Shared Sub Main()
		Dim reader As StreamReader = Nothing
		Try
			reader = New StreamReader("example.txt")
			Dim content As String = reader.ReadToEnd()
			Console.WriteLine(content)
		Finally
			\static-assets\pdf\blog\csharp-using\csharp-using-2.webp
			If reader IsNot Nothing Then
				reader.Dispose()
			End If
		End Try
	End Sub
End Class
$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#
    }
}
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語句。 每個資源都需要其自己的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語句的另一個好處是它幫助更輕鬆地處理異常。 如果在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語句

IronPDF是一個受歡迎的用於在C#和.NET應用程序中創建、編輯和提取PDF文件的庫。 像其他處理資源的庫一樣,IronPDF也可以利用using語句來確保正確的資源管理。

讓我們來探討如何使用using語句與IronPDF從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文件在完成提取文本後被正確關閉,即使過程中發生異常。 這是如using語句如何有效地管理C#資源的一個好例子。

C# Using Statement

總結

這就是使用using語句的簡短介紹! 我們已經看到它如何確保以高效的方式處理可處置對象,無縫管理一個或多個資源。 using語句不僅有助於保持代碼的整潔,還增強了您的C#項目的可讀性。

我們還介紹了IronPDF,一個強大的C# PDF操作庫。 使用using語句與IronPDF結合,展示了這一代碼特性的實際應用,加強了這一概念及其重要性。

準備好試用 IronPDF 嗎? 您可以開始我們的IronPDF和Iron Software's Suite的30天免費試用。 它的開發用途完全免費,因此您可以真正看到它的作用。 如果您喜歡,目前IronPDF的價格僅從$799的許可選項開始。 欲獲得更大的優惠,請查看Iron Suite完整軟件包,您可以以兩個工具的價格獲得Iron Software的全部九個工具。 祝您編程愉快!

IronPDF Using Statement

常見問題解答

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

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

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

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

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

using 區塊用大括號括住代碼,並且在區塊結尾時自動釋放資源,而從 C# 8.0 開始引入的 using 宣告則更簡潔,會在資源超出作用域時自動釋放資源。

如何在我的自訂 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天免費試用版,並且可免費用於開發用途,讓您在購買前探索其功能。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。