.NET 幫助

C# 物件導向(對開發人員的運作方式)

里根普恩
里根普恩
2024年4月3日
分享:

面向物件程式設計 (物件導向程式設計)是軟體開發中的一個基本概念,使程式設計師能夠創建模組化、可重用和適應性的代碼。 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();
    }
}

在這個範例中,Car 類別有兩個數據成員(名稱顏色)和一個方法(顯示信息). Main 方法作為應用程式的進入點,創建一個 Car 類別的實例,並在調用其方法顯示這些值之前給其字段賦值。

C# 物件導向(它對開發人員的運作方式):圖 1 - 控制台通過 DisplayInfo 方法顯示 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();
    }
}

在此範例中,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 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 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; } 
}

在本例中,name 欄位是私有的,使其在 Person 類之外無法訪問。 可以通過公共 Name 屬性訪問此欄位,其中包括 getset 方法。

實用案例和編碼範例

現在,我們將探討一個涉及多個類別的範例,以展示這些原則的實際應用。

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.");
        }
    }
}

在此範例中,Drive()是從 Vehicle 抽象類別中繼承的抽象方法Car 是一個實作 Drive 的衍生類別(),以及 ElectricCar 是層級中的另一個層次,增加了新功能,例如 BatteryLevel 以及其自身的 Drive() 實施。 此結構展示了抽象化、封裝、繼承和多型性在 C# 應用程式中的協同運作。

C# 面向物件 (給開發者的運作方式):圖 2 - 程式碼的控制台輸出,顯示來自 drive 抽象方法和 charge 方法的輸出

IronPDF:C# PDF 庫

IronPDF 程式庫 for .NET是專為C#開發人員設計的多功能工具,旨在簡化在.NET應用程式中創建、編輯和提取PDF文件的過程。 IronPDF 能夠輕鬆從 HTML 字串生成 PDF、URL 或 ASPX 文件,提供對 PDF 創建和操作過程的高控制度。 此外,IronPDF 支持進階功能,例如添加頁首和頁尾、浮水印和加密,使其成為在 .NET 應用程式中處理 PDF 的全面解決方案。

IronPDF 與面向對象程式設計的範例

以下是一個簡化的範例,展示如何在 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.");
    }
}

在此範例中,BasicReportGenerator 有一個方法 GenerateReport,該方法接受 HTML 內容並使用 IronPDF 生成 PDF 文件。 CustomReportGenerator 類別從 BasicReportGenerator 繼承,重寫了 GenerateReport 方法,以在基類方法生成 PDF 後添加自定義標題。 以下是由程式碼生成的自訂報告:

C# 面向對象 (對開發人員的作用):圖 3 - 從代碼示例生成的自定義 PDF,展示了文章中討論的 OOP 方法

結論

C# 面向對象(它對開發人員的工作原理):圖 4 - IronPDF 許可頁面

透過理解和應用面向對象程式設計(OOP)的基本原則,初學者可以在掌握C#和開發健全的軟體解決方案方面邁出重要的一步。 繼承和多型允許程式碼重用和靈活性,讓新類別可以構建在現有的結構和功能之上。 抽象化和封裝確保類別只向外界暴露必要的部分,保持內部運作的私密性,防止意外使用。 您可以嘗試使用 IronPDFC#中的PDF生成免費試用,可從 liteLicense 開始提供。

里根普恩
軟體工程師
Regan 畢業於雷丁大學,擁有電子工程學士學位。在加入 Iron Software 之前,他的工作角色讓他專注於單一任務;而他在 Iron Software 工作中最喜歡的是他所能承擔的工作範圍,無論是增加銷售價值、技術支持、產品開發或市場營銷。他喜歡了解開發人員如何使用 Iron Software 庫,並利用這些知識不斷改進文檔和開發產品。
< 上一頁
C#操作(開發者如何運作)
下一個 >
C# String.Join(開發者如何使用)