C# 使用(开发者如何使用)
即使您刚开始接触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);
}
}
}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 ClassImports 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在这个例子中,名为reader的StreamReader对象被包裹在一个using块中。 当退出using块时,会自动调用reader的Dispose方法,释放其所持有的任何资源。
Using块与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 ClassImports 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使用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 ModuleImports 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如您所见,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 ClassImports 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注意: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 ClassImports 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在这个例子中,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 ClassFriend Class Program
Shared Sub Main()
Using resource As New CustomResource("example.txt")
resource.ReadContent()
End Using
End Sub
End Class当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 ClassImports 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在这种情况下,如果代码引发FileNotFoundException,该异常将在catch块中被捕获并处理。 即使异常发生在using块中,Dispose方法仍会在StreamReader对象上调用,确保没有资源泄漏。
使用IronPDF和Using语句
IronPDF是一个流行的库,用于在C#和.NET应用程序中创建、编辑和提取PDF文件。 如同其他处理资源的库一样,IronPDF也可以从using语句中受益,以确保适当的资源管理。
让我们探索如何使用using语句与IronPDF一起从HTML字符串创建PDF文档,展示using语句在实际生活中的强大功能。
首先,确保您已在项目中安装了IronPDF的NuGet包:
现在,让我们从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 ClassImports 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在此代码中,我们使用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了吗? 您可以从我们的IronPDF和Iron Software套件的30天免费试用版开始。 它也完全免费用于开发目的,因此您可以真正了解它的功能。 如果您喜欢所见,IronPDF起价低至$999查看许可选项。 为了获得更大的节省,请查看Iron Suite完整软件包,您可以以两款软件的价格获取Iron Software的九种工具。 祝您编码愉快!
Jacob Mellor是Iron Software的首席技术官,也是C# PDF技术的先锋工程师。作为Iron Software核心代码库的原始开发者,自公司成立以来,他就一直在塑造公司的产品架构,与首席执行官Cameron Rimington一起将其转型为拥有50多人、服务于NASA、特斯拉和全球政府机构的公司。