C# 面向對象(對於開發者的運行原理)
物件導向程式設計 (OOP) 是軟體開發的基本概念,可讓程式設計師建立模組化、可重複使用且可調整的程式碼。 C# 是一種現代的物件導向程式語言,為建立複雜的應用程式提供了強大的框架。 本指南使用 C# 介紹 OOP 概念,著重於實用的實作和編碼範例,幫助初學者有效地理解和應用這些原則。 我們也將討論如何將這些原則應用在 IronPDF library for 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 類有兩個資料成員 (Name 和 Color) 和一個方法 (DisplayInfo)。 作為應用程式入口點的 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。
多態性與抽象:介面與抽象類。
多態性可讓物件以其基類而非特定類別的實體來處理。 抽象(Abstraction)允許您定義抽象類別和介面,這些類別和介面無法實體化,但可以作為基類使用。
抽象類和方法
抽象類無法實體化,通常用來提供基類的共同定義,讓多個派生類可以共用。
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");
}
}
Public Interface IDrawable
Sub Draw()
End Interface
Public Interface IColorable
Sub Color()
End Interface
Public Class CustomShape ' Defining a new class CustomShape that implements IDrawable and IColorable.
Implements IDrawable, IColorable
Public Sub Draw() Implements IDrawable.Draw
Console.WriteLine("Custom shape drawn")
End Sub
Public Sub Color() Implements IColorable.Color
Console.WriteLine("Custom shape colored")
End Sub
End Class
封裝:保護資料
封裝(Encapsulation)是一種限制存取物件某些元件,並防止外部人士看到內部表示的機制。 這可以透過使用存取變數來達成。
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 類別之外無法存取。 透過包含 get 和 set 方法的公用 Name 屬性可存取此欄位。
實用案例與編碼範例
現在,我們將探討一個涉及多個類別的範例,以實際證明這些原則。
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:C# PDF 函式庫
IronPDF library for .NET 是專為 C# 開發人員設計的多功能工具,可簡化在 .NET 應用程式中建立、編輯和擷取 PDF 文件的流程。 IronPDF 具備從 HTML 字串、URL 或 ASPX 檔案輕易地產生 PDF的能力,提供對 PDF 建立與操作流程的高度控制。 此外,IronPDF 支援添加頁首和頁尾、水印和加密等進階功能,使其成為在 .NET 應用程式中處理 PDF 的全面解決方案。
使用 OOP 的 IronPDF 示例
以下是一個簡化的範例,說明如何在 C# 應用程式中使用 IronPDF,並結合 virtual 關鍵字來說明如何透過繼承(OOP 的核心概念)來擴展 IronPDF 的功能。假設我們有一個產生基本 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 之後,將自訂標頭新增至 PDF。 以下是程式碼產生的自訂報告:
。
結論
。
透過了解並應用 OOP 的基本原則,初學者可以朝向掌握 C# 並開發健全的軟體解決方案邁出重要的一步。 繼承與多態性可讓程式碼重複使用且具有彈性,讓新的類別建立在現有的結構與功能上。 抽象與封裝可確保類別僅向外界揭露必要的內容,並保持內部運作的隱密性,避免意外使用。 您可以試試 IronPDF免費試用版,試用版可在 C# 中產生 PDF ,從 liteLicense 開始提供。
常見問題解答
如何在 C# 中應用面向物件程式設計原則?
在 C# 中,您可以透過定義類別和物件來模擬現實世界中的實體以應用面向物件程式設計原則。 使用繼承來擴展類別,使用多型來允許方法覆寫,並使用封裝來保護資料,從而創建模組化和可維護的代碼。
抽象在 C# 程式設計中扮演什麼角色?
C# 中的抽象允許開發人員簡化複雜系統,通過明確區分抽象的高階概念和具體實現。 抽象類別和介面用於為其他類別定義藍圖,確保應用程式不同部分的結構和行為一致。
如何在 C# 中使用面向物件原則創建 PDF 報告?
您可以使用 IronPDF 庫在 C# 中創建 PDF 報告,該庫允許您從 HTML 內容生成 PDF 文件。 通過運用面向物件原則,您可以為報告生成創建基類,並透過派生類添加特定功能,例如添加自訂的標頭或頁尾。
在 C# 中使用封裝有什麼好處?
C# 中的封裝提供了透過限制對物件內部元件的存取來保護物件資料的優勢。 這是使用存取修飾符實現的,有助於維護資料的完整性並防止程式的其他部分進行未預期的干擾。
如何在 C# 應用程式中通過多型來實現?
在 C# 中,可以透過在派生類別中使用方法覆寫來實現多型。 這允許您在基類中定義方法並在派生類別中覆寫方法,提供靈活性,並允許物件被視為它們基類的實例。
如何擴展 C# 中的 PDF 庫的功能?
您可以透過創建自訂類別來擴展像 IronPDF 這樣的 PDF 庫的功能,這些類別實現了附加功能。 例如,您可以創建一個從基類 PDF 生成類繼承的類別,並添加方法以自訂 PDF 頁面的外觀或內容。
您能否提供一個使用 C# 繼承的程式碼示例?
C# 繼承的程式碼示例可能涉及定義一個基類 `Vehicle`,其包含 `Speed` 和 `Fuel` 等屬性。 派生類 `Car` 可以擴展 `Vehicle` 並添加如 `NumberOfDoors` 的具體功能。 這展示了派生類如何繼承和擴展基類的功能。
IronPDF 如何與 C# 中的面向物件程式設計集成?
IronPDF 透過允許開發者創建封裝 PDF 生成邏輯的類別來與 C# 中的面向物件程式設計集成。 您可以為常見的 PDF 操作定義基類,並透過繼承和多型擴展它們的特定功能,如添加水印或自訂格式。



