.NET 帮助

C# Casting(如何为开发人员工作)

发布 2024年十二月15日
分享:

C# # Casting 简介

铸造在 C# 中,"转换 "是一项强大的功能,允许开发人员将一种数据类型的变量转换为另一种数据类型。 它在面向对象编程中发挥着至关重要的作用,尤其是在处理继承层次结构或使用接口时。 在使用像IronPDF对于 PDF 操作而言,理解铸造对于有效管理各种类型的 PDF 元素和操作至关重要

在本文中,我们将探讨 C# 中铸造的概念、其意义以及在使用 IronPDF 时如何应用。 最后,您将了解如何利用铸造增强您的 PDF 处理能力并简化您的开发流程。 我们鼓励您试用 IronPDF 免费试用版,亲身体验这些优势。

理解 C&num 中的铸造;

隐式铸造与显式铸造

在 C# 中,铸造大致可分为两种类型: 隐式转换和显式转换**。

  • 隐式转换:这是指编译器自动执行的转换。 它是安全的,不会导致数据丢失。 例如,转换较小的数据类型(如整数变量)到更大的类型(如双变量)是隐含的:
int myInt = 10; // Integer variable
    double myDouble = myInt; // Implicit casting from int to double
int myInt = 10; // Integer variable
    double myDouble = myInt; // Implicit casting from int to double
Dim myInt As Integer = 10 ' Integer variable
	Dim myDouble As Double = myInt ' Implicit casting from int to double
VB   C#

这一过程通常被称为自动转换,因为 C# 编译器无需开发人员的任何明确指令即可处理。

  • 显式转换:这需要进行铸模操作,在从较大的类型转换到较小的类型时是必要的,因为这可能会导致数据丢失。 例如
double myDouble = 9.78;
    int myInt = (int)myDouble; // Explicit casting from double to int
double myDouble = 9.78;
    int myInt = (int)myDouble; // Explicit casting from double to int
Imports System

Dim myDouble As Double = 9.78
	Dim myInt As Integer = CInt(Math.Truncate(myDouble)) ' Explicit casting from double to int
VB   C#

在这种情况下,开发人员必须说明他们打算将数据类型转换为另一种类型,因此称为显式类型转换。

常见翻译场景

铸造常用于涉及基类和派生类的场景。 例如,在处理类层次结构时,可以将派生类对象转换为基类类型:

class Base { }
class Derived : Base { }
Derived derived = new Derived();
Base baseRef = derived; // Implicit casting to base class
class Base { }
class Derived : Base { }
Derived derived = new Derived();
Base baseRef = derived; // Implicit casting to base class
Friend Class Base
End Class
Friend Class Derived
	Inherits Base

End Class
Private derived As New Derived()
Private baseRef As Base = derived ' Implicit casting to base class
VB   C#

使用 IronPDF 时,在处理各种 PDF 相关类时,如要将通用 PDF 对象转换为更特定的类型以访问某些属性或方法时,铸造是必不可少的。

铸造 IronPDF

安装 IronPDF

开始使用IronPDF请注意,您首先需要安装它。 如果已经安装,则可以跳到下一节,否则,以下步骤将介绍如何安装 IronPDF 库。

通过 NuGet 软件包管理器控制台

安装 IronPdf使用 NuGet 软件包管理器控制台,打开 Visual Studio 并导航到软件包管理器控制台。 然后运行以下命令:

Install-Package IronPdf
Install-Package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package IronPdf
VB   C#

通过 NuGet 软件包管理器获取解决方案

打开 Visual Studio,进入 "工具 -> NuGet 包管理器 -> 管理解决方案的 NuGet 包 "并搜索 IronPdf。 在这里,您只需选择您的项目并点击 "安装",IronPDF 就会添加到您的项目中。

破损图片 添加自 Pixabay,请从您的文件中选择或将图片拖放到此处。

安装 IronPDF 后,只需在代码顶部添加正确的 using 语句即可开始使用 IronPDF:

using IronPdf;
using IronPdf;
Imports IronPdf
VB   C#

使用 PDF 文档对象

IronPDF 提供了多个操作 PDF 文档的类,如PdfDocument, ChromePdfRendererPDFPage. 了解这些类型如何通过铸造进行交互对于有效操作 PDF 至关重要。

例如,您可能有一个通用的 PdfDocument 对象集合,需要使用一个特定的 PdfPage 对象。 您可以通过铸造来实现这一目标:

PdfDocument pdfDoc = new PdfDocument(210, 297);
PdfPage page = (PdfPage)pdfDoc.Pages[0]; // Casting a generic PDF page to a specific type
PdfDocument pdfDoc = new PdfDocument(210, 297);
PdfPage page = (PdfPage)pdfDoc.Pages[0]; // Casting a generic PDF page to a specific type
Dim pdfDoc As New PdfDocument(210, 297)
Dim page As PdfPage = CType(pdfDoc.Pages(0), PdfPage) ' Casting a generic PDF page to a specific type
VB   C#

通过该铸件,您可以访问 PdfPage 特有的属性和方法,从而增强对 PDF 内容的控制。

示例:行动中的铸造

让我们看看下面的示例,我们需要从 PDF 中提取文本并适当转换对象:

using IronPdf;
using IronPdf.Pages;
using System;
public static void Main(string[] args)
{
    PdfDocument pdf = PdfDocument.FromFile("example.pdf");
    foreach (PdfPage page in pdf.Pages)
    {
        PdfPage pdfPage = (PdfPage)page;
        string text = pdfPage.Text;
        Console.WriteLine($"Text from Page {pdfPage.PageIndex}: {text}");
    }
}
using IronPdf;
using IronPdf.Pages;
using System;
public static void Main(string[] args)
{
    PdfDocument pdf = PdfDocument.FromFile("example.pdf");
    foreach (PdfPage page in pdf.Pages)
    {
        PdfPage pdfPage = (PdfPage)page;
        string text = pdfPage.Text;
        Console.WriteLine($"Text from Page {pdfPage.PageIndex}: {text}");
    }
}
Imports IronPdf
Imports IronPdf.Pages
Imports System
Public Shared Sub Main(ByVal args() As String)
	Dim pdf As PdfDocument = PdfDocument.FromFile("example.pdf")
	For Each page As PdfPage In pdf.Pages
		Dim pdfPage As PdfPage = CType(page, PdfPage)
		Dim text As String = pdfPage.Text
		Console.WriteLine($"Text from Page {pdfPage.PageIndex}: {text}")
	Next page
End Sub
VB   C#

输入 PDF:

C# Casting(如何为开发人员工作):图 2

控制台输出

C# Casting(如何为开发人员工作):图 3

在此示例中,我们加载 PDF 文档,遍历其页面,并将每个页面转换为 PdfPage 以提取文本内容。 其中重点介绍了铸造如何使您能够使用 IronPDF 类的特定属性和方法。

C# 和 num 中铸造的最佳实践;

避免 InvalidCastException

在进行转换时,必须确保转换是有效的,以避免在运行时出现 InvalidCastException。以下是一些最佳实践:

  1. 使用 as 关键字:使用该关键字,您可以尝试转置,而不会在转置失败时抛出异常。 而不是返回空值。
PdfPage pdfPage = page as PdfPage; // Safe cast
    if (pdfPage != null)
    {
        // Proceed with pdfPage
    }
PdfPage pdfPage = page as PdfPage; // Safe cast
    if (pdfPage != null)
    {
        // Proceed with pdfPage
    }
Dim pdfPage As PdfPage = TryCast(page, PdfPage) ' Safe cast
	If pdfPage IsNot Nothing Then
		' Proceed with pdfPage
	End If
VB   C#
  1. 使用 is 进行类型检查:在铸造之前,您可以使用 is 关键字检查对象的类型。
if (page is PdfPage)
    {
        PdfPage pdfPage = (PdfPage)page; // Safe cast after type check
    }
if (page is PdfPage)
    {
        PdfPage pdfPage = (PdfPage)page; // Safe cast after type check
    }
If TypeOf page Is PdfPage Then
		Dim pdfPage As PdfPage = CType(page, PdfPage) ' Safe cast after type check
End If
VB   C#
  1. 用户自定义转换:C# 允许开发人员通过用户定义的转换为自定义类定义自己的铸造规则。 当您希望以更直观的方式在不同的用户定义类型之间进行转换时,这一点尤其有用。
public class MyCustomType
    {
        public static explicit operator MyCustomType(int value)
        {
            return new MyCustomType(/* conversion logic */);
        }
    }
    int myInt = 5;
    MyCustomType myCustomType = (MyCustomType)myInt; // Using explicit user defined conversion
public class MyCustomType
    {
        public static explicit operator MyCustomType(int value)
        {
            return new MyCustomType(/* conversion logic */);
        }
    }
    int myInt = 5;
    MyCustomType myCustomType = (MyCustomType)myInt; // Using explicit user defined conversion
Public Class MyCustomType
		Public Shared Narrowing Operator CType(ByVal value As Integer) As MyCustomType
			Return New MyCustomType()
		End Operator
End Class
	Private myInt As Integer = 5
	Private myCustomType As MyCustomType = CType(myInt, MyCustomType) ' Using explicit user defined conversion
VB   C#

性能考虑事项

虽然铸造通常是高效的,但过度或不必要的铸造会导致性能问题,尤其是在涉及大型集合或复杂对象的情况下。 优化性能:

  • 尽可能使用最具体的类型,从而最大限度地减少语法转换。
  • 避免在对性能至关重要的循环中进行铸造,而是在可行的情况下缓存结果。
  • 尽可能利用内置方法进行类型转换,因为它们通常可以提供更优化的性能。

结论

铸造是 C# 编程的一个重要方面,尤其是在使用 IronPDF 等库进行 PDF 操作时。 通过了解隐式和显式铸造以及采用最佳实践,您可以提高有效管理 PDF 对象的能力。

利用 IronPDF 的功能和适当的铸造可以简化工作流程,使您能够轻松、精确地处理 PDF 内容。 要开始亲自探索 IronPDF 的广泛功能,请务必查看免费试用.

< 前一页
C# Exponent(如何为开发人员工作)
下一步 >
如何在 C# 中将字符串转换为 Int(开发人员教程)