跳至页脚内容
.NET 帮助

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);
        }
    }
}
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块与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方法仍会被自动调用。

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\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块中,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 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块时,会自动调用PdfDocument实例的Dispose方法,以释放其持有的任何资源。

通过在PdfDocument中使用using语句,我们确保在完成文本提取后即使在过程中出现异常,PDF文件也能被正确关闭。 这是一个使用using语句有效管理C#中资源的好例子。

C# Using语句

总结

这就是using语句的一次简洁的浏览! 我们已看到它如何确保可释放对象的有效处理,顺畅地管理一个或多个资源。 using语句不仅有助于维护更清晰的代码,还增强了您的C#项目的可读性。

我们还介绍了IronPDF,这是一个用于C#的强大PDF操作库。 将using语句与IronPDF结合使用,展示了这种代码功能的实际应用,加强了概念及其重要性。

准备好亲自体验IronPDF了吗? 您可以从我们的IronPDF和Iron Software套件的30天免费试用版开始。 它也完全免费用于开发目的,因此您可以真正了解它的功能。 如果您喜欢所见,IronPDF的起步价仅为$799,提供多种许可选项。 为了获得更大的节省,请查看Iron Suite完整软件包,您可以以两款软件的价格获取Iron Software的九种工具。 祝您编码愉快!

IronPDF Using语句

常见问题解答

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 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。