.NET 幫助

C# 使用 (對開發者的運作方式)

發佈 2024年8月15日
分享:

即使您剛剛開始學習 C#,您可能已經遇到過 using 指令。而如果您是 IronPDF 用戶,您會非常熟悉用命名空間開頭的程式碼:using ironpdf。

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

使用在 C# 中是什麼?

using 語句在 C# 中是一種便捷用於處理實現 IDisposable 介面的資源的方法。IDisposable 物件通常會保存未受控資源,例如文件句柄或網絡連接,這些資源在使用完後需要被釋放。這就是使用 using 語句的真正意圖所在 - 它幫助您確保這些資源在使用後能夠正確地釋放。

使用 using 陳述式的運作方式

當您使用 using 陳述式時,C# 會在物件不再需要時自動呼叫 Dispose 方法。這意味著您不需要手動呼叫 Dispose 方法或擔心忘記這麼做。using 陳述式會為您處理這些事情。!

讓我們來看一個簡單的例子,看看 using 語句是如何運作的:

   using System.IO;

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

   class Program
   {
       static void Main()
       {
           using (StreamReader reader = new StreamReader("example.txt"))
           {
               string content = reader.ReadToEnd();
               Console.WriteLine(content);
           }
       }
   }
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

在此範例中,名為 reader 的 StreamReader 物件包裹在 using 區塊中。當 using 區塊結束時,會自動呼叫 reader 上的 Dispose 方法,釋放其佔用的所有資源。

使用區塊 vs. 使用宣告

從 C# 8.0 開始,您可以使用使用宣告代替使用區塊。使用宣告是一種更簡短且更簡潔的方式來定義可釋放的物件,如下所示:

   using System.IO;

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

   class Program
   {
       static void Main()
       {
           using var reader = new StreamReader("example.txt");
           string content = reader.ReadToEnd();
           Console.WriteLine(content);
       }
   }
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

使用 using 宣告時,不需要使用大括號或縮排,讓您的程式碼更具可讀性。當變數超出範圍時,Dispose 方法仍會自動被調用。

Try Block, Finally Block, and the Using Statement

嘗試區塊, 最後區塊, 和使用語句

你可能想知道在 C# 中使用語句與 try 和 finally 區塊有什麼關係。其實,使用語句就是 try-finally 區塊的簡寫。!

以下是相同的示例,但使用 try-finally 區塊而不是使用 using 語句:

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.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();
               }
           }
       }
   }
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

如您所見,using 語句通過消除對 try-finally 區塊以及顯式呼叫 Dispose 方法的需求,使代碼變得更清晰、更易讀。

管理多個資源

使用 using 語句的其中一個好處就是它可以同時處理多個資源。你可以一個接一個地堆疊 using 語句,也可以使用單一個 using 語句來處理以逗號分隔列表中的多個資源。以下是一個展示這兩種方法的範例:

   using System.IO;

   class Program
   {
       static void Main()t
       {
           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}");
           }

           // Alternatively, you can use a single using statement with multiple resources:

           using (StreamReader reader1 = new StreamReader("example1.txt"), reader2 = new StreamReader("example2.txt"))
           {
               string content1 = reader1.ReadToEnd();
               string content2 = reader2.ReadToEnd();
               Console.WriteLine($"Content from example1.txt:\n{conten1}\nContent from example2.txt:\n{content2}");
           }
       }
   }
   using System.IO;

   class Program
   {
       static void Main()t
       {
           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}");
           }

           // Alternatively, you can use a single using statement with multiple resources:

           using (StreamReader reader1 = new StreamReader("example1.txt"), reader2 = new StreamReader("example2.txt"))
           {
               string content1 = reader1.ReadToEnd();
               string content2 = reader2.ReadToEnd();
               Console.WriteLine($"Content from example1.txt:\n{conten1}\nContent from example2.txt:\n{content2}");
           }
       }
   }
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

這兩種方法都將確保在退出 using 區塊時,對每個 StreamReader 對象調用了 Dispose 方法,釋放它們佔用的任何資源。

實作 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;
           }
       }
   }
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

在這個例子中,CustomResource 類別管理一個 StreamReader 物件,這是一個可釋放的物件。透過實現 IDisposable 介面並實現 Dispose 方法,我們可以使用 using 語句來處理這個類別的實例。

以下是如何使用 using 語句來處理 CustomResource 類別:

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();
       }
   }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

當使用區塊終止時,將調用 Dispose 方法,處理它管理的 StreamReader 物件。

使用語句處理異常

使用語句的另一個好處是它能更優雅地處理異常。 如果在 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}");
       }
   }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

在這種情況下,如果程式碼拋出 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 (PdfDocument pdfDocument = PdfDocument.FromFile("PDFData.pdf"))
       {
           string extractedText = pdfDocument.ExtractAllText();
           Console.WriteLine(extractedText);
       }
   }
}
using IronPdf;

class Program
{
   static void Main()
   {
       using (PdfDocument pdfDocument = PdfDocument.FromFile("PDFData.pdf"))
       {
           string extractedText = pdfDocument.ExtractAllText();
           Console.WriteLine(extractedText);
       }
   }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

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

在 using 區塊內,我們調用 PdfDocument 實例的 ExtractAllText 方法來提取 PDF 中的所有文字。當退出 using 區塊時,會自動調用 PdfDocument 的 Dispose 方法,釋放其佔用的所有資源。

通過將 PdfDocument 與 using 語句結合使用,我們確保在完成文字提取後正確關閉 PDF 檔案,即使在過程中發生例外情況,這也是 using 語句在 C# 中有效管理資源的良好示例。

結論

這是使用 using 語句的一個簡短概覽。! 我們已經看到它如何確保對臨時物件的高效處理,無縫地管理一個或多個資源。using 語句不僅有助於保持代碼的清潔,還提高了你的 C# 項目的可讀性。

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

準備好開始使用 IronPDF 了嗎?你可以從我們的 30 天免費試用它也可以完全免費用於開發目的,讓您可以真正了解它的性能。如果您喜歡所見,IronPDF的價格低至 $749欲享受更多優惠,請查看 Iron Suite 在這裡,您可以以兩個的價格獲得全部九個Iron Software工具。祝編程愉快!

< 上一頁
C# 擴充方法(開發人員如何使用)
下一個 >
Visual C++ 可再发行程序包是什麼

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >