.NET 幫助

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

發佈 2024年4月3日
分享:

在 C# 中, 虛擬 關鍵字 是物件導向程式設計中的一個重要概念,它促進了多型性,使開發人員可以在派生類別中覆蓋方法。這個關鍵字應用於類別方法、屬性或事件時,表示該實體可以由派生類別使用 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
VB   C#

覆蓋虛方法

派生類別可以覆蓋這些虛方法,提供其自己的實現,以適應派生類別的具體需求。使用 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
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 方法,展現了透過虛擬和覆寫關鍵字所實現的動態分派機制。

C# 虛擬關鍵字(對開發者的工作原理):圖 1 - 來自上述代碼的控制台輸出顯示了 myCircle 如何調用重寫的 Area 方法

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

抽象方法和類別

抽象方法更進一步,用於抽象類別中。抽象方法是在基類中聲明但沒有實現的方法,必須在派生類別中重寫。它強制派生類別為抽象方法提供實現,確保一致的介面,同時允許每個派生類別中的自訂行為。

方法重載與覆寫的區別

了解方法重載與方法覆寫之間的區別也非常重要。方法重載發生在同一個類中,允許多個方法具有相同的名稱但不同的參數。方法覆寫則是透過 virtualoverride 關鍵字實現,允許派生類別為基底類別中定義的方法提供不同的實現。

虛擬屬性和事件

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

IronPDF: .NET PDF 庫

IronPDF 是一個專為C#開發者設計的綜合庫,可在.NET應用程式中直接生成、操作和渲染PDF文件。它提供了一個直觀的API,簡化了 處理 PDF 文件幫助開發人員在不需要了解複雜的底層 PDF 文件結構或求助於外部軟體的情況下創建、編輯和轉換 PDF。IronPDF 無縫整合了該語言的面向對象功能,包括使用 virtual 關鍵字,提供可自定義的 PDF 處理能力。

使用 IronPDF 的 virtual 關鍵字可以讓開發人員在他們的應用程式中擴展 IronPDF 類別的功能。通過定義具有與 PDF 生成或操作相關的 virtual 方法的基類,開發人員可以創建覆蓋這些方法的派生類,以根據具體需求定制 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 類會覆寫此方法,不僅執行轉換,還 injects a distinct, large, red 在生成的 PDF 添加浮水印.

輸出 PDF 文件

這是由 IronPDF 生成的 PDF 文件:

C# Virtual 關鍵字(如何讓開發人員使用):圖 2 - 使用虛擬方法 RenderHtmlToPDF 從 CustomPdfRenderer 進行轉換的範例代碼輸出

結論

C# Virtual Keyword(開發人員使用方式):圖 3 - IronPDF 授權頁面

C#中的virtual關鍵字是面向對象編程的基石,使多態性和動態調度成為可能。通過允許派生類提供基類中定義的方法、屬性和事件的具體實現,它賦予開發人員創建靈活且可重用代碼結構的能力。通過實際例子和理解虛方法、覆蓋機制以及類層次結構之間的關係,開發人員可以在構建健壯應用程序時有效利用這些概念。此外,這些概念還能幫助開發人員在應用程序中更高效地使用IronPDF。您可以使用其免費測試IronPDF。 免費試用 成本為 $749 及以上。

< 上一頁
C# 泛型(适用于开发人员的运作方式)
下一個 >
NativeUI C#(對開發者的運作方式)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >