.NET 帮助

C# 面向对象(它如何为开发人员工作)

发布 2024年四月3日
分享:

面向对象的程序设计 (OOP) 是软件开发中的一个基本概念,它使程序员能够创建模块化、可重用和可调整的代码。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#

在本例中,类有两个数据成员 (名称颜色) 和一种方法 (DisplayInfo).作为应用程序入口的 Main 方法创建了一个 Car 类实例,并为其字段赋值,然后调用其方法来显示这些值。

C# 面向对象(如何为开发人员工作):图 1 - 控制台通过 DisplayInfo 方法显示汽车对象的成员值(名称、颜色

继承:扩展现有类

继承允许类继承现有类的属性和方法。属性被继承的类称为基类,继承了这些属性的类称为派生类。

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#

在本例中,驱动器() 是车辆抽象类的一个抽象方法。 汽车是一个派生类,它实现了驱动()电动汽车是另一个层级,增加了电池级别和自己的驱动器等新功能。() 实现。这种结构展示了抽象、封装、继承和多态性在 C# 应用程序中的协同作用。

C# 面向对象(如何为开发人员工作):图 2 - 代码的控制台输出,打印驱动抽象方法和充电方法的输出

IronPDF:C# PDF Library

IronPDF IronPDF 是一款面向 C# 开发人员的多功能库,旨在简化在 .NET 应用程序中创建、编辑和提取 PDF 文档的过程。IronPDF 具有以下功能 从 HTML 字符串生成 PDFIronPDF 支持 PDF、URL 或 ASPX 文件,可对 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
VB   C#

在本例中,BasicReportGenerator 有一个方法 GenerateReport,该方法使用 IronPDF 获取 HTML 内容并生成 PDF 文档。CustomReportGenerator类继承自BasicReportGenerator,它覆盖了GenerateReport方法,以便在基本方法生成 PDF 后添加自定义标题。下面是代码生成的自定义报告:

C# 面向对象(如何为开发人员工作):图 3 - 根据代码示例生成的自定义 PDF,显示了文章中讨论的 OOP 方法的套用情况

结论

C# 面向对象(如何为开发人员工作):图 4 - IronPDF 许可页面

通过理解和应用 OOP 的基本原则,初学者可以在掌握 C# 和开发强大的软件解决方案方面迈出重要的一步。继承和多态可以实现代码的重用和灵活性,让新的类建立在现有结构和功能的基础上。抽象和封装确保类只向外界暴露必要的内容,保持内部运作的私密性,避免意外使用。您可以试用 IronPDF 免费试用,可从 $749 开始使用。

< 前一页
C# 操作(开发人员如何使用)
下一步 >
C# String.Join(它如何为开发人员工作)

准备开始了吗? 版本: 2024.10 刚刚发布

免费NuGet下载 总下载量: 11,108,738 查看许可证 >