.NET 帮助

C# Virtual 关键字(对开发者的作用)

发布 2024年四月3日
分享:

在 C# 中 虚拟关键字 是面向对象编程中的一个重要概念,它促进了多态性,允许开发人员覆盖派生类中的方法。当该关键字应用于一个类的方法、属性或事件时,表示该实体可以被使用覆盖关键字的派生类修改其行为。在本教程中,我们将学习 C# 虚拟关键字和 IronPDF 库。 让我们直接了解它的工作原理,并通过实际例子来了解它的操作。

虚拟方法在行动

虚拟关键词的基本用法

虚拟方法的核心是基类方法,它允许派生类为基类中已定义的方法提供特定的实现。

C# 中的 virtual 关键字将方法、属性或事件标记为虚拟,表示可以在继承该方法、属性或事件的任何类中重载该方法、属性或事件。请看下面的示例,我们定义了一个基类 Shape,其中包含一个虚拟方法 Area

public class Shape
{
    public virtual double Area()
    {
        return 0; // Default implementation, returns 0
    }
}
public class Shape
{
    public virtual double Area()
    {
        return 0; // Default implementation, returns 0
    }
}
Public Class Shape
	Public Overridable Function Area() As Double
		Return 0 ' Default implementation, returns 0
	End Function
End Class
VB   C#

覆盖虚拟方法

派生类可以覆盖这些虚拟方法,根据派生类的具体要求提供自己的实现。使用覆盖关键字,让我们创建一个 Circle 类,该类派生于 Shape,并提供自己版本的 Area 方法:

public class Circle : Shape
{
    public double Radius { get; set; }
    public Circle(double radius)
    {
        Radius = radius;
    }
    public override double Area()
    {
        return Math.PI * Radius * Radius; // Own implementation for circle area
    }
}
public class Circle : Shape
{
    public double Radius { get; set; }
    public Circle(double radius)
    {
        Radius = radius;
    }
    public override double Area()
    {
        return Math.PI * Radius * Radius; // Own implementation for circle area
    }
}
Public Class Circle
	Inherits Shape

	Public Property Radius() As Double
	Public Sub New(ByVal radius As Double)
		Me.Radius = radius
	End Sub
	Public Overrides Function Area() As Double
		Return Math.PI * Radius * Radius ' Own implementation for circle area
	End Function
End Class
VB   C#

在上述代码中,Circle 类提供了Area 方法的特定实现,该方法用于计算圆的面积。这展示了虚拟方法在多态性中的威力。

非虚拟方法

需要注意的是,并非所有方法都需要或应该是虚拟方法。非虚拟方法的定义方式是派生类不能重载该方法,这意味着初始实现保持不变,并被所有继承该方法的类所使用。当基类提供了不应更改的标准实现时,这种方法就非常有用。

实际应用

让我们将这些概念应用到实际场景中。请看下面这个使用了 ShapeCircle 类的程序:

public class Program
{
    public static void Main(string [] args)
    {
        Shape myShape = new Shape();
        Shape myCircle = new Circle(5);
        Console.WriteLine($"Shape area: {myShape.Area()}");
        Console.WriteLine($"Circle area: {myCircle.Area()}");
    }
}
public class Program
{
    public static void Main(string [] args)
    {
        Shape myShape = new Shape();
        Shape myCircle = new Circle(5);
        Console.WriteLine($"Shape area: {myShape.Area()}");
        Console.WriteLine($"Circle area: {myCircle.Area()}");
    }
}
Public Class Program
	Public Shared Sub Main(ByVal args() As String)
		Dim myShape As New Shape()
		Dim myCircle As Shape = New Circle(5)
		Console.WriteLine($"Shape area: {myShape.Area()}")
		Console.WriteLine($"Circle area: {myCircle.Area()}")
	End Sub
End Class
VB   C#

上面的示例程序展示了多态性的作用和虚拟函数的本质。尽管myCircle被声明为一个Shape,但它调用了Circle类中被覆盖的Area方法,展示了由 virtual 和 override 关键字促成的动态调度机制。

C# 虚拟关键字(开发人员如何使用):图 1 - 上述代码的控制台输出,展示了 myCircle 如何调用重载的 Area 方法

虚拟和覆盖关键字的高级用法

抽象方法和类

抽象方法是在抽象类中使用的更进一步的方法。抽象方法是在基类中声明的方法,没有实现,必须在派生类中重写。它迫使派生类为抽象方法提供一个实现,从而确保了接口的一致性,同时允许每个派生类自定义行为。

Method Overloading vs. Overriding

了解方法重载和方法重载之间的区别也很重要。方法重载发生在同一个类中,允许多个方法具有相同的名称但不同的参数。方法重载通过 virtual 和 override 关键字实现,允许派生类为基类中定义的方法提供不同的实现。

虚拟属性和事件

除了方法,属性和事件也可以是虚拟的。这使得派生类可以提供自定义的获取器、设置器和事件处理程序,从而进一步提高类层次结构的灵活性。

IronPDF:.NET PDF 库

IronPDF 是一个综合库,专为 C# 开发人员设计,用于在 .NET 应用程序中直接生成、处理和渲染 PDF 文档。它提供了一个直观的应用程序接口,可简化 处理 PDF 文件IronPDF 可帮助开发人员创建、编辑和转换 PDF,而无需了解复杂的底层 PDF 文档结构或借助外部软件。IronPDF 与面向对象语言的功能(包括虚拟关键字的使用)无缝集成,提供可定制的 PDF 处理功能。

使用 IronPDF 的虚拟关键字,开发人员可以在其应用程序中扩展 IronPDF 类的功能。通过定义带有与 PDF 生成或操作相关的虚拟方法的基类,开发人员可以创建覆盖这些方法的派生类,从而根据特定需求定制 PDF 处理行为。

示例:使用虚拟方法自定义 PDF 渲染

想象一下,您有一个使用 IronPDF 从 HTML 字符串渲染 PDF 的基类。通过将渲染方法标记为虚拟方法,您可以让派生类修改或增强渲染过程。下面是一个简单的例子:

public class BasicPdfRenderer
{
    // Virtual method allowing customization in derived classes
    public virtual byte [] RenderHtmlToPdf(string htmlContent)
    {
        // Use IronPDF to render PDF from HTML
        var renderer = new IronPdf.ChromePdfRenderer();
        var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
        return pdfDocument.BinaryData;
    }
}
public class CustomPdfRenderer : BasicPdfRenderer
{
    // Overriding the base class method to implement custom rendering settings
    public override byte [] RenderHtmlToPdf(string htmlContent)
    {
        var renderer = new IronPdf.ChromePdfRenderer();
        var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
        // Apply a prominent watermark to the PDF document
        pdfDocument.ApplyWatermark("<h2 style='color:red; font-size: 60px; opacity: 0.5; text-shadow: 2px 2px 5px grey;'>SAMPLE</h2>",
                                      30,
                                      IronPdf.Editing.VerticalAlignment.Middle,
                                      IronPdf.Editing.HorizontalAlignment.Center);
        // Return the binary data of the PDF document
        return pdfDocument.BinaryData;
    }
}
class Program
{
    static void Main(string [] args)
    {
        License.LicenseKey = "License-Key";
        // HTML content to be converted to PDF
        string htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a simple PDF document generated from HTML.</p>";
        // Create an instance of CustomPdfRenderer
        CustomPdfRenderer renderer = new CustomPdfRenderer();
        // Call RenderHtmlToPdf method to generate PDF binary data
        byte [] pdfData = renderer.RenderHtmlToPdf(htmlContent);
        // Specify the file path to save the PDF
        string filePath = "f:\\CustomRenderedPdf.pdf";
        // Save the binary data to a file
        File.WriteAllBytes(filePath, pdfData);
        Console.WriteLine($"PDF generated and saved to {filePath}");
    }
}
public class BasicPdfRenderer
{
    // Virtual method allowing customization in derived classes
    public virtual byte [] RenderHtmlToPdf(string htmlContent)
    {
        // Use IronPDF to render PDF from HTML
        var renderer = new IronPdf.ChromePdfRenderer();
        var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
        return pdfDocument.BinaryData;
    }
}
public class CustomPdfRenderer : BasicPdfRenderer
{
    // Overriding the base class method to implement custom rendering settings
    public override byte [] RenderHtmlToPdf(string htmlContent)
    {
        var renderer = new IronPdf.ChromePdfRenderer();
        var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
        // Apply a prominent watermark to the PDF document
        pdfDocument.ApplyWatermark("<h2 style='color:red; font-size: 60px; opacity: 0.5; text-shadow: 2px 2px 5px grey;'>SAMPLE</h2>",
                                      30,
                                      IronPdf.Editing.VerticalAlignment.Middle,
                                      IronPdf.Editing.HorizontalAlignment.Center);
        // Return the binary data of the PDF document
        return pdfDocument.BinaryData;
    }
}
class Program
{
    static void Main(string [] args)
    {
        License.LicenseKey = "License-Key";
        // HTML content to be converted to PDF
        string htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a simple PDF document generated from HTML.</p>";
        // Create an instance of CustomPdfRenderer
        CustomPdfRenderer renderer = new CustomPdfRenderer();
        // Call RenderHtmlToPdf method to generate PDF binary data
        byte [] pdfData = renderer.RenderHtmlToPdf(htmlContent);
        // Specify the file path to save the PDF
        string filePath = "f:\\CustomRenderedPdf.pdf";
        // Save the binary data to a file
        File.WriteAllBytes(filePath, pdfData);
        Console.WriteLine($"PDF generated and saved to {filePath}");
    }
}
Public Class BasicPdfRenderer
	' Virtual method allowing customization in derived classes
	Public Overridable Function RenderHtmlToPdf(ByVal htmlContent As String) As Byte()
		' Use IronPDF to render PDF from HTML
		Dim renderer = New IronPdf.ChromePdfRenderer()
		Dim pdfDocument = renderer.RenderHtmlAsPdf(htmlContent)
		Return pdfDocument.BinaryData
	End Function
End Class
Public Class CustomPdfRenderer
	Inherits BasicPdfRenderer

	' Overriding the base class method to implement custom rendering settings
	Public Overrides Function RenderHtmlToPdf(ByVal htmlContent As String) As Byte()
		Dim renderer = New IronPdf.ChromePdfRenderer()
		Dim pdfDocument = renderer.RenderHtmlAsPdf(htmlContent)
		' Apply a prominent watermark to the PDF document
		pdfDocument.ApplyWatermark("<h2 style='color:red; font-size: 60px; opacity: 0.5; text-shadow: 2px 2px 5px grey;'>SAMPLE</h2>", 30, IronPdf.Editing.VerticalAlignment.Middle, IronPdf.Editing.HorizontalAlignment.Center)
		' Return the binary data of the PDF document
		Return pdfDocument.BinaryData
	End Function
End Class
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		License.LicenseKey = "License-Key"
		' HTML content to be converted to PDF
		Dim htmlContent As String = "<h1>Hello, IronPDF!</h1><p>This is a simple PDF document generated from HTML.</p>"
		' Create an instance of CustomPdfRenderer
		Dim renderer As New CustomPdfRenderer()
		' Call RenderHtmlToPdf method to generate PDF binary data
		Dim pdfData() As Byte = renderer.RenderHtmlToPdf(htmlContent)
		' Specify the file path to save the PDF
		Dim filePath As String = "f:\CustomRenderedPdf.pdf"
		' Save the binary data to a file
		File.WriteAllBytes(filePath, pdfData)
		Console.WriteLine($"PDF generated and saved to {filePath}")
	End Sub
End Class
VB   C#

我们在BasicPdfRenderer类中使用IronPDF将HTML转换为PDF,并将其RenderHtmlToPdf方法标记为虚拟方法,以便进行自定义。从BasicPdfRenderer派生而来的CustomPdfRenderer类重载了该方法,不仅可以执行转换,还可以注入一个明显的、大的、红色的 "IronPDF"。 在生成的 PDF 上添加水印.

输出 PDF 文件

这是 IronPDF 生成的 PDF 文件:

C# 虚拟关键字(如何为开发人员工作):图 2 - 利用 CustomPdfRendered 的虚拟方法 RenderHtmlToPDF 进行转换的代码输出示例

结论

C# 虚拟关键字(如何为开发人员工作):图 3 - IronPDF 许可页面

C# 中的虚拟关键字是面向对象编程的基石,可实现多态性和动态调度。通过允许派生类提供基类中定义的方法、属性和事件的特定实现,它使开发人员能够创建灵活和可重用的代码结构。通过实际示例和了解虚拟方法、覆盖机制和类层次结构之间的关系,开发人员可以有效地利用这些概念构建强大的应用程序。此外,这些概念还有助于开发人员在其应用程序中更有效地使用 IronPDF。您可以使用 IronPDF 的 免费试用 费用为 $749 及以上。

< 前一页
C# 泛型(开发者如何使用)
下一步 >
NativeUI C#(开发者指南)

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

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