.NET 幫助

C# 虛擬關鍵字(開發人員如何使用)

在 C# 中,virtual 關鍵字 是物件導向程式設計中的核心概念,它促進了多型,允許開發者在衍生類別中覆寫方法。 當這個關鍵字應用於類別的方法、屬性或事件時,表示該實體的行為可以由派生類別使用 override 關鍵字進行修改。 在本教程中,我們將學習 C# 的 Virtual 關鍵字並探索 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
$vbLabelText   $csharpLabel

重寫虛擬方法

派生類別可以覆蓋這些虛擬方法,以提供其自己的實現,針對派生類別的具體需求進行定制。 使用 override 關鍵字,讓我們創建一個從 Shape 派生並提供其自身版本的 Area 方法的 Circle 類別:

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
$vbLabelText   $csharpLabel

在上述代碼中,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
$vbLabelText   $csharpLabel

上述範例程式展示了多型的應用及虛擬函式的精髓。 儘管myCircle被宣告為Shape,但它調用了來自Circle類別的被覆寫的Area方法,展示了由 virtual 和 override 關鍵字促成的動態調度機制。

C# Virtual Keyword(其運作方式適用於開發人員): 圖 1 - 來自上述代碼的控制台輸出,展示了 myCircle 如何調用重寫的 Area 方法

虛擬和重寫關鍵字的高級用法

抽象方法和類別

抽象方法是抽象類別中的一個進一步使用的步驟。 抽象方法是在基類中聲明而未實現的方法,必須在衍生類中重寫。 它強制衍生類別提供抽象方法的實現,確保一致的介面,同時允許每個衍生類別提供定制化的行為。

方法重載 vs. 方法覆寫

了解方法重載和方法覆蓋之間的區別也很重要。 方法重載是在同一個類別中發生的,允許多個方法擁有相同的名稱但具有不同的參數。 透過 virtual 和 override 關鍵字實現的方法覆寫,允許衍生類別為基類中定義的方法提供不同的實作。

虛擬屬性和事件

除了方法之外,屬性和事件也可以是虛擬的。 這使得衍生類別能夠提供自訂的 getter、setter 和事件處理器,進一步增強類別層次結構的靈活性。

IronPDF:.NET PDF 圖書館

IronPDF 是一個綜合性函式庫,專為 C# 開發者設計,用於在 .NET 應用程式中生成、操作和渲染 PDF 文件。 它提供了一個直觀的 API,簡化了使用 HTML 創建 PDF 等 PDF 文件的操作,幫助開發者創建、編輯和轉換 PDF,無需了解複雜的底層 PDF 文件結構或依賴外部軟件。 IronPDF 無縫整合了該語言的物件導向功能,包括使用 virtual 關鍵字,以提供可自訂的 PDF 處理功能。

使用 virtual 關鍵字搭配 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
$vbLabelText   $csharpLabel

我們在 BasicPdfRenderer 類中使用 IronPDF 將 HTML 轉換為 PDF,並將其 RenderHtmlToPdf 方法標記為虛擬,以允許自訂。 CustomPdfRenderer 類別從 BasicPdfRenderer 繼承,覆寫此方法不僅進行轉換,還在生成的 PDF 上注入一個獨特的大紅色浮水印

輸出 PDF 文件

這是由 IronPDF 生成的 PDF 文件:

C# 虛擬關鍵字(它如何為開發人員工作):圖 2 - 使用虛擬方法 RenderHtmlToPDF 從 CustomPdfRendered 進行轉換的示例代碼輸出

結論

C# Virtual 關鍵字(開發人員如何使用):圖 3 - 了解 IronPDF 的授權過程

C# 中的虛擬(virtual)關鍵字是物件導向程式設計的基石,能實現多型和動態派遣。 通過允許衍生類別提供基類中定義的方法、屬性和事件的具體實現,它賦予開發者創建靈活且可重複使用的程式碼結構的能力。 通過實際範例和理解虛擬方法、覆寫機制與類別層次結構之間的關係,開發人員可以有效地將這些概念應用於構建穩健的應用程式。 此外,這些概念還將有助於開發人員在他們的應用程式中更有效地使用IronPDF。 您可以使用其免費試用選項來測試IronPDF,而不需要花費任何費用。

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
C# 泛型(适用于开发人员的运作方式)
下一個 >
NativeUI C#(對開發者的運作方式)