.NET 幫助

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

發佈 2024年4月3日
分享:

面向物件程式設計 (物件導向程式設計) 是軟體開發中的一個基本概念,允許程式員創建模塊化、可重用和可適應的代碼。C#是一種現代對象導向的編程語言,提供了一個構建複雜應用程序的強大框架。本指南介紹了使用C#的OOP概念,聚焦於實際的實施和編碼範例,以幫助初學者有效地理解和應用這些原則。我們還將討論如何使用這些原則應用於 IronPDF 庫.

了解面向对象编程的概念

面向对象编程的核心是几个关键概念:类、对象、继承、多态、抽象和封装。这些概念允许开发人员模拟现实世界实体,管理复杂性,并提高代码的可维护性。

類別和對象:構建模塊

類別創建個別的對象。類別是一個藍圖,定義了該類別對象共享的數據和行為。對象是類別的具體表現。它具體化了真實的數據值,而不是類別藍圖中定義的抽象佔位符。

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 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 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 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
VB   C#

在這個範例中,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();
    }
}
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
VB   C#

在此範例中,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
VB   C#

實作多個介面

介面建立了一種協議或合約,類別可以透過實作其定義的方法來實現。類別可以實作多個介面,從而實現一種多型。

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
VB   C#

封裝: 保護資料

封裝是一種限制對物件某些組件的存取,並防止外部人士查看內部表示的機制。這是通過使用存取修飾符來實現的。

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
VB   C#

在此範例中,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.");
        }
    }
}
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
VB   C#

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

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

IronPDF:C# PDF 庫

IronPDF 是一個多功能的庫,專為C#開發者設計,以簡化在.NET應用程式內創建、編輯和提取PDF文件的過程。IronPDF具有輕鬆 從 HTML 字串生成 PDF,URLs,或ASPX文件,提供了對PDF創建和操作過程的高度控制。此外,IronPDF支持添加頁眉和頁腳、水印和加密等高級功能,這使其成為在.NET應用程式中處理PDF的全面解決方案。

IronPDF 與物件導向程式設計的範例

以下是一個簡化的範例,展示了在 C# 應用程式中使用 IronPDF,並結合 virtual 關鍵字,說明如何通過繼承來擴展 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
VB   C#

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

C# 面向物件(對開發人員的運作方式):圖3 - 由程式碼範例生成的自訂PDF,展示了文章中討論的OOP方法

結論

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

通過理解和應用物件導向程式設計(OOP)的基本原則,初學者可以在掌握 C# 和開發強健的軟體解決方案方面邁出重要的一步。繼承與多態性允許了程式碼的重用和靈活性,讓新的類別可以建立在現有結構和功能之上。抽象與封裝確保類別只向外部暴露必要的部分,保持內部運作私密並防止未經授權的使用。您可以嘗試 IronPDF。 免費試用,這從 $749 開始提供。

< 上一頁
C#操作(開發者如何運作)
下一個 >
C# String.Join(開發者如何使用)

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

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