.NET幫助 C# 面向對象(對於開發者的運行原理) Jacob Mellor 更新:7月 28, 2025 下載 IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 開始免費試用 法學碩士副本 法學碩士副本 將頁面複製為 Markdown 格式,用於 LLMs 在 ChatGPT 中打開 請向 ChatGPT 諮詢此頁面 在雙子座打開 請向 Gemini 詢問此頁面 在雙子座打開 請向 Gemini 詢問此頁面 打開困惑 向 Perplexity 詢問有關此頁面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 複製連結 電子郵件文章 物件導向程式設計 (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 $vbLabelText $csharpLabel 在這個範例中,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 $vbLabelText $csharpLabel 在這個範例中,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 $vbLabelText $csharpLabel 實作多重介面 介面建立了一個協議或合約,類別可以透過實作其定義的方法來履行。 類別可以實作多個介面,從而實現一種多態性。 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 $vbLabelText $csharpLabel 封裝:保護資料 封裝(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 $vbLabelText $csharpLabel 在這個範例中,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 $vbLabelText $csharpLabel 在這個範例中,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 $vbLabelText $csharpLabel 在這個範例中,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 與 C# 的物件導向程式整合,允許開發人員建立封裝 PDF 產生邏輯的類別。您可以定義常用 PDF 作業的基本類別,並使用繼承與多態性,以特定功能來擴充這些類別,例如新增水印或自訂格式。 Jacob Mellor 立即與工程團隊聊天 首席技术官 Jacob Mellor 是 Iron Software 的首席技術官,作為 C# PDF 技術的先鋒工程師。作為 Iron Software 核心代碼的原作者,他自開始以來塑造了公司產品架構,與 CEO Cameron Rimington 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。Jacob 持有曼徹斯特大學土木工程一級榮譽学士工程學位(BEng) (1998-2001)。他於 1999 年在倫敦開設了他的第一家軟件公司,並於 2005 年製作了他的首個 .NET 組件,專注於解決 Microsoft 生態系統內的複雜問題。他的旗艦產品 IronPDF & Iron Suite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。 相關文章 更新12月 11, 2025 銜接 CLI 簡化與 .NET : 使用 Curl DotNet 與 IronPDF for .NET Jacob Mellor 藉由 CurlDotNet 彌補了這方面的不足,CurlDotNet 是為了讓 .NET 生態系統能熟悉 cURL 而建立的函式庫。 閱讀更多 更新9月 4, 2025 RandomNumberGenerator C# 使用RandomNumberGenerator C#類可以幫助將您的PDF生成和編輯項目提升至新水準 閱讀更多 更新9月 4, 2025 C#字符串等於(它如何對開發者起作用) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 C# Action(對於開發者的運行原理)C# String.Join(對於開發者的...
更新12月 11, 2025 銜接 CLI 簡化與 .NET : 使用 Curl DotNet 與 IronPDF for .NET Jacob Mellor 藉由 CurlDotNet 彌補了這方面的不足,CurlDotNet 是為了讓 .NET 生態系統能熟悉 cURL 而建立的函式庫。 閱讀更多