在實際環境中測試
在生產環境中測試無浮水印。
在任何需要的地方都能運作。
面向物件程式設計 (物件導向程式設計)是軟體開發中的一個基本概念,使程式設計師能夠創建模組化、可重用和適應性的代碼。 C#是一種現代的物件導向程式語言,提供了一個強大的框架來構建複雜的應用程式。 本指南使用 C# 介紹物件導向程式設計(OOP)的概念,重點在於實際的實現和編碼範例,以幫助初學者有效理解並應用這些原則。 我們還將討論如何將這些原則應用於IronPDF 程式庫適用於 C#.
OOP的核心包含幾個關鍵概念:類別、物件、繼承、多型、抽象和封裝。 這些概念使開發人員能夠模擬現實世界的實體,管理複雜性,並提升其代碼的可維護性。
一個類別會創建個別的物件。 類別是一個藍圖,定義了類別物件所共有的數據和行為。 物件是類別的具現體。 它代表了真正的值,而不是在類藍圖中定義的抽象佔位符。
public class Car // A class declared as 'Car' defines its structure and behavior.
{
public string Name;
public string Color;
public void DisplayInfo()
{
Console.WriteLine($"Name: {Name}, Color: {Color}");
}
}
class Program // This is the program class, serving as the entry point of a C# program.
{
static void Main(string [] args)
{
Car myCar = new Car();
myCar.Name = "Toyota";
myCar.Color = "Red";
myCar.DisplayInfo();
}
}
public class Car // A class declared as 'Car' defines its structure and behavior.
{
public string Name;
public string Color;
public void DisplayInfo()
{
Console.WriteLine($"Name: {Name}, Color: {Color}");
}
}
class Program // This is the program class, serving as the entry point of a C# program.
{
static void Main(string [] args)
{
Car myCar = new Car();
myCar.Name = "Toyota";
myCar.Color = "Red";
myCar.DisplayInfo();
}
}
Public Class Car ' A class declared as 'Car' defines its structure and behavior.
Public Name As String
Public Color As String
Public Sub DisplayInfo()
Console.WriteLine($"Name: {Name}, Color: {Color}")
End Sub
End Class
Friend Class Program ' This is the program class, serving as the entry point of a C# program.
Shared Sub Main(ByVal args() As String)
Dim myCar As New Car()
myCar.Name = "Toyota"
myCar.Color = "Red"
myCar.DisplayInfo()
End Sub
End Class
在這個範例中,Car 類別有兩個數據成員(名稱 和 顏色)和一個方法(顯示信息). Main 方法作為應用程式的進入點,創建一個 Car 類別的實例,並在調用其方法顯示這些值之前給其字段賦值。
繼承允許一個類別繼承現有類別的屬性和方法。 擁有被繼承屬性的類別稱為基礎類別,而繼承這些屬性的類別稱為衍生類別。
public class Vehicle
{
public string LicensePlate;
public void Honk()
{
Console.WriteLine("Honking");
}
}
public class Truck : Vehicle // Truck is a child class derived from the Vehicle base class.
{
public int CargoCapacity;
}
class Program
{
static void Main(string [] args)
{
Truck myTruck = new Truck();
myTruck.LicensePlate = "ABC123";
myTruck.CargoCapacity = 5000;
myTruck.Honk();
}
}
public class Vehicle
{
public string LicensePlate;
public void Honk()
{
Console.WriteLine("Honking");
}
}
public class Truck : Vehicle // Truck is a child class derived from the Vehicle base class.
{
public int CargoCapacity;
}
class Program
{
static void Main(string [] args)
{
Truck myTruck = new Truck();
myTruck.LicensePlate = "ABC123";
myTruck.CargoCapacity = 5000;
myTruck.Honk();
}
}
Public Class Vehicle
Public LicensePlate As String
Public Sub Honk()
Console.WriteLine("Honking")
End Sub
End Class
Public Class Truck ' Truck is a child class derived from the Vehicle base class.
Inherits Vehicle
Public CargoCapacity As Integer
End Class
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim myTruck As New Truck()
myTruck.LicensePlate = "ABC123"
myTruck.CargoCapacity = 5000
myTruck.Honk()
End Sub
End Class
在此範例中,Truck 是一個衍生類別,擴展了 Vehicle 基礎類別,繼承了其 LicensePlate 欄位和 Honk 方法,同時增加了一個新欄位 CargoCapacity。
多型允許物件被視為其基類的實例,而不是其具體類別的實例。 抽象允許您定義無法實例化但可以用作基類的抽象類和接口。
抽象類別不能被實例化,通常用來提供基礎類別的通用定義,以供多個衍生類別共享。
public abstract class Shape
{
public abstract void Draw();
}
public class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a circle");
}
}
public abstract class Shape
{
public abstract void Draw();
}
public class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a circle");
}
}
Public MustInherit Class Shape
Public MustOverride Sub Draw()
End Class
Public Class Circle
Inherits Shape
Public Overrides Sub Draw()
Console.WriteLine("Drawing a circle")
End Sub
End Class
介面建立了一份協議或合同,類別可以透過實現其定義的方法來履行。 類別可以實作多個介面,實現一種多型的形式。
public interface IDrawable
{
void Draw();
}
public interface IColorable
{
void Color();
}
public class CustomShape : IDrawable, IColorable // Defining a new class CustomShape that implements IDrawable and IColorable.
{
public void Draw()
{
Console.WriteLine("Custom shape drawn");
}
public void Color()
{
Console.WriteLine("Custom shape colored");
}
}
public interface IDrawable
{
void Draw();
}
public interface IColorable
{
void Color();
}
public class CustomShape : IDrawable, IColorable // Defining a new class CustomShape that implements IDrawable and IColorable.
{
public void Draw()
{
Console.WriteLine("Custom shape drawn");
}
public void Color()
{
Console.WriteLine("Custom shape colored");
}
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
封裝是限制對物件某些組件的訪問並防止外部方查看內部表示的機制。 這是透過使用訪問修飾符來完成的。
public class Person
{
private string name; // Private variable, inaccessible outside the class
public string Name // Public property to access the private variable
{
get { return name; }
set { name = value; }
}
}
// Example showing a simple customer class with encapsulated data
public class Customer
{
public string Name { get; set; }
public string Address { get; set; }
}
public class Person
{
private string name; // Private variable, inaccessible outside the class
public string Name // Public property to access the private variable
{
get { return name; }
set { name = value; }
}
}
// Example showing a simple customer class with encapsulated data
public class Customer
{
public string Name { get; set; }
public string Address { get; set; }
}
Public Class Person
'INSTANT VB NOTE: The field name was renamed since Visual Basic does not allow fields to have the same name as other class members:
Private name_Conflict As String ' Private variable, inaccessible outside the class
Public Property Name() As String ' Public property to access the private variable
Get
Return name_Conflict
End Get
Set(ByVal value As String)
name_Conflict = value
End Set
End Property
End Class
' Example showing a simple customer class with encapsulated data
Public Class Customer
Public Property Name() As String
Public Property Address() As String
End Class
在本例中,name 欄位是私有的,使其在 Person 類之外無法訪問。 可以通過公共 Name 屬性訪問此欄位,其中包括 get 和 set 方法。
現在,我們將探討一個涉及多個類別的範例,以展示這些原則的實際應用。
using System;
namespace OOPExample
{
public class Program
{
static void Main(string [] args)
{
ElectricCar myElectricCar = new ElectricCar();
myElectricCar.Make = "Tesla";
myElectricCar.Model = "Model 3";
myElectricCar.BatteryLevel = 100;
myElectricCar.Drive();
myElectricCar.Charge();
}
}
public abstract class Vehicle
{
public string Make { get; set; }
public string Model { get; set; }
public abstract void Drive();
}
public class Car : Vehicle
{
public override void Drive()
{
Console.WriteLine($"The {Make} {Model} is driving.");
}
}
public class ElectricCar : Car
{
public int BatteryLevel { get; set; }
public void Charge()
{
Console.WriteLine("Charging the car.");
}
public override void Drive()
{
Console.WriteLine($"The {Make} {Model} is driving silently.");
}
}
}
using System;
namespace OOPExample
{
public class Program
{
static void Main(string [] args)
{
ElectricCar myElectricCar = new ElectricCar();
myElectricCar.Make = "Tesla";
myElectricCar.Model = "Model 3";
myElectricCar.BatteryLevel = 100;
myElectricCar.Drive();
myElectricCar.Charge();
}
}
public abstract class Vehicle
{
public string Make { get; set; }
public string Model { get; set; }
public abstract void Drive();
}
public class Car : Vehicle
{
public override void Drive()
{
Console.WriteLine($"The {Make} {Model} is driving.");
}
}
public class ElectricCar : Car
{
public int BatteryLevel { get; set; }
public void Charge()
{
Console.WriteLine("Charging the car.");
}
public override void Drive()
{
Console.WriteLine($"The {Make} {Model} is driving silently.");
}
}
}
Imports System
Namespace OOPExample
Public Class Program
Shared Sub Main(ByVal args() As String)
Dim myElectricCar As New ElectricCar()
myElectricCar.Make = "Tesla"
myElectricCar.Model = "Model 3"
myElectricCar.BatteryLevel = 100
myElectricCar.Drive()
myElectricCar.Charge()
End Sub
End Class
Public MustInherit Class Vehicle
Public Property Make() As String
Public Property Model() As String
Public MustOverride Sub Drive()
End Class
Public Class Car
Inherits Vehicle
Public Overrides Sub Drive()
Console.WriteLine($"The {Make} {Model} is driving.")
End Sub
End Class
Public Class ElectricCar
Inherits Car
Public Property BatteryLevel() As Integer
Public Sub Charge()
Console.WriteLine("Charging the car.")
End Sub
Public Overrides Sub Drive()
Console.WriteLine($"The {Make} {Model} is driving silently.")
End Sub
End Class
End Namespace
在此範例中,Drive()是從 Vehicle 抽象類別中繼承的抽象方法。 Car 是一個實作 Drive 的衍生類別(),以及 ElectricCar 是層級中的另一個層次,增加了新功能,例如 BatteryLevel 以及其自身的 Drive() 實施。 此結構展示了抽象化、封裝、繼承和多型性在 C# 應用程式中的協同運作。
這IronPDF 程式庫 for .NET是專為C#開發人員設計的多功能工具,旨在簡化在.NET應用程式中創建、編輯和提取PDF文件的過程。 IronPDF 能夠輕鬆從 HTML 字串生成 PDF、URL 或 ASPX 文件,提供對 PDF 創建和操作過程的高控制度。 此外,IronPDF 支持進階功能,例如添加頁首和頁尾、浮水印和加密,使其成為在 .NET 應用程式中處理 PDF 的全面解決方案。
以下是一個簡化的範例,展示如何在 C# 應用程式中使用 IronPDF,並結合 virtual 關鍵字,來說明如何透過繼承來擴展 IronPDF 的功能,這是物件導向程式設計 (OOP) 的核心概念。我們假設有一個基礎類別,可以生成基本的 PDF 報告,以及一個衍生類別來擴展此功能以包含自定義標題:
using IronPdf;
public class BasicReportGenerator
{
public virtual PdfDocument GenerateReport(string htmlContent)
{
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
return pdf;
}
}
public class CustomReportGenerator : BasicReportGenerator
{
public override PdfDocument GenerateReport(string htmlContent)
{
var pdf = base.GenerateReport(htmlContent);
AddCustomHeader(pdf, "Custom Report Header");
return pdf;
}
private void AddCustomHeader(PdfDocument document, string headerContent)
{
// Create text header
TextHeaderFooter textHeader = new TextHeaderFooter
{
CenterText = headerContent,
};
document.AddTextHeaders(textHeader);
}
}
class Program
{
static void Main(string [] args)
{
License.LicenseKey = "License-Key";
// HTML content for the report
string htmlContent = "<html><body><h1>Sample Report</h1><p>This is a sample report content.</p></body></html>";
// Using BasicReportGenerator
BasicReportGenerator basicReportGenerator = new BasicReportGenerator();
var basicPdf = basicReportGenerator.GenerateReport(htmlContent);
basicPdf.SaveAs("basic_report.pdf");
// Using CustomReportGenerator
CustomReportGenerator customReportGenerator = new CustomReportGenerator();
var customPdf = customReportGenerator.GenerateReport(htmlContent);
customPdf.SaveAs("custom_report.pdf");
Console.WriteLine("PDF reports generated successfully.");
}
}
using IronPdf;
public class BasicReportGenerator
{
public virtual PdfDocument GenerateReport(string htmlContent)
{
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
return pdf;
}
}
public class CustomReportGenerator : BasicReportGenerator
{
public override PdfDocument GenerateReport(string htmlContent)
{
var pdf = base.GenerateReport(htmlContent);
AddCustomHeader(pdf, "Custom Report Header");
return pdf;
}
private void AddCustomHeader(PdfDocument document, string headerContent)
{
// Create text header
TextHeaderFooter textHeader = new TextHeaderFooter
{
CenterText = headerContent,
};
document.AddTextHeaders(textHeader);
}
}
class Program
{
static void Main(string [] args)
{
License.LicenseKey = "License-Key";
// HTML content for the report
string htmlContent = "<html><body><h1>Sample Report</h1><p>This is a sample report content.</p></body></html>";
// Using BasicReportGenerator
BasicReportGenerator basicReportGenerator = new BasicReportGenerator();
var basicPdf = basicReportGenerator.GenerateReport(htmlContent);
basicPdf.SaveAs("basic_report.pdf");
// Using CustomReportGenerator
CustomReportGenerator customReportGenerator = new CustomReportGenerator();
var customPdf = customReportGenerator.GenerateReport(htmlContent);
customPdf.SaveAs("custom_report.pdf");
Console.WriteLine("PDF reports generated successfully.");
}
}
Imports IronPdf
Public Class BasicReportGenerator
Public Overridable Function GenerateReport(ByVal htmlContent As String) As PdfDocument
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)
Return pdf
End Function
End Class
Public Class CustomReportGenerator
Inherits BasicReportGenerator
Public Overrides Function GenerateReport(ByVal htmlContent As String) As PdfDocument
Dim pdf = MyBase.GenerateReport(htmlContent)
AddCustomHeader(pdf, "Custom Report Header")
Return pdf
End Function
Private Sub AddCustomHeader(ByVal document As PdfDocument, ByVal headerContent As String)
' Create text header
Dim textHeader As New TextHeaderFooter With {.CenterText = headerContent}
document.AddTextHeaders(textHeader)
End Sub
End Class
Friend Class Program
Shared Sub Main(ByVal args() As String)
License.LicenseKey = "License-Key"
' HTML content for the report
Dim htmlContent As String = "<html><body><h1>Sample Report</h1><p>This is a sample report content.</p></body></html>"
' Using BasicReportGenerator
Dim basicReportGenerator As New BasicReportGenerator()
Dim basicPdf = basicReportGenerator.GenerateReport(htmlContent)
basicPdf.SaveAs("basic_report.pdf")
' Using CustomReportGenerator
Dim customReportGenerator As New CustomReportGenerator()
Dim customPdf = customReportGenerator.GenerateReport(htmlContent)
customPdf.SaveAs("custom_report.pdf")
Console.WriteLine("PDF reports generated successfully.")
End Sub
End Class
在此範例中,BasicReportGenerator 有一個方法 GenerateReport,該方法接受 HTML 內容並使用 IronPDF 生成 PDF 文件。 CustomReportGenerator 類別從 BasicReportGenerator 繼承,重寫了 GenerateReport 方法,以在基類方法生成 PDF 後添加自定義標題。 以下是由程式碼生成的自訂報告:
透過理解和應用面向對象程式設計(OOP)的基本原則,初學者可以在掌握C#和開發健全的軟體解決方案方面邁出重要的一步。 繼承和多型允許程式碼重用和靈活性,讓新類別可以構建在現有的結構和功能之上。 抽象化和封裝確保類別只向外界暴露必要的部分,保持內部運作的私密性,防止意外使用。 您可以嘗試使用 IronPDFC#中的PDF生成免費試用,可從 liteLicense
開始提供。