.NET 帮助

C# 使用(开发者如何运作)

发布 2024年八月15日
分享:

即使你刚开始学习 C#,你可能已经遇到过 using 指令。如果你是 IronPDF 的用户,你会非常熟悉使用 using ironpdf 命名空间来启动代码。

然而,using 关键字还有另一个用途。在本指南中,我们将介绍 using 语句——它是什么,如何工作,以及如何帮助你创建更高效的代码。让我们深入探讨一下。!

什么是C#中的 Using?

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 块退出时,Dispose 方法会自动在 reader 上被调用,释放它占用的所有资源。

使用块与使用声明

从C# 8.0开始,您可以使用using声明代替using块。using声明是一种更短更简洁的方式来定义可释放对象,如下所示:

   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 块、Finally 块以及 Using 语句

您可能想知道 using 语句如何与 C# 中的 try 和 finally 块相关。事实上,using 语句实际上是 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语句。

以下是如何在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();
       }
   }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

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

在这种情况下,如果代码抛出FileNotFoundException异常,该异常将由catch块捕获并处理。即使异常发生在using块内,Dispose方法仍然会在StreamReader对象上调用,确保没有资源泄漏。

使用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操作的强大库。将using 语句与IronPDF结合使用,展示了这一代码特性的实际应用,加强了概念及其重要性。

准备好上手使用IronPDF了吗?你可以从我们的 30 天免费试用开发端也是完全免费的,所以您可以真正了解它的性能。而且,如果您喜欢它,IronPDF 的起价仅为 $749欲获得更大折扣,请查看 Iron Suite 在这里,您可以以两款工具的价格获得Iron Software的全部九款工具。祝编程愉快。!

< 前一页
C#扩展方法(开发人员如何使用)
下一步 >
什么是 Visual C++ 可再发行组件

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >