跳至页脚内容
.NET 帮助

C# 面向对象(开发人员如何使用)

面向对象编程(OOP)是软件开发中的一个基本概念,使程序员能够创建模块化、可重用和适应性强的代码。 C#是一种现代面向对象编程语言,提供了一个用于构建复杂应用程序的健壮框架。 本指南使用C#介绍OOP概念,重点是实用的实现和代码示例,帮助初学者有效地理解和应用这些原则。 我们还将讨论如何在C#的IronPDF库中应用这些原则。

理解面向对象编程概念

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类有两个数据成员(NameColor)和一个方法(DisplayInfo)。 Main方法作为应用程序的入口点,创建Car类的一个实例,并在调用其方法显示这些值之前给其字段赋值。

C# 面向对象(对开发者的工作方式):图1 - 控制台通过DisplayInfo方法显示Car对象的成员值(name、color)

继承:扩展现有类

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

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

多态和抽象:接口和抽象类

多态性使对象可以作为其基类而不是特定类的实例处理。 抽象允许定义抽象类和接口,这些类和接口不能实例化但可以用作基类。

抽象类和方法

抽象类不能实例化,通常用于提供多个派生类可以共享的基类的通用定义。

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

封装:保障数据安全

封装是限制访问对象的某些组件并防止外部方查看内部表示的机制。 这是通过使用访问修饰符完成的。

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类外部不可访问。 通过包括getset方法的公共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#应用中的协作工作。

C# 面向对象(对开发者的工作方式):图2 - 控制台显示代码输出,打印驱动抽象方法和充电方法的输出

探索 IronPDF 用于 PDF 管理 是一个为使用 C# 编程语言的开发人员提供的工具,允许他们在其应用程序内部直接创建、读取和编辑 PDF 文档。

IronPDF库 for .NET 是一个为C#开发人员设计的多功能工具,旨在简化在.NET应用程序中创建、编辑和提取PDF文档的过程。 IronPDF能够轻松从HTML字符串、URLs 或 ASPX文件生成PDF,提供了高水平的PDF创建和操作过程的控制。 此外,IronPDF支持添加页眉和页脚、水印和加密等高级功能,是在.NET应用程序中处理PDF的全面解决方案。

IronPDF与OOP示例

这是一个简化的示例,演示了在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.");
    }
}
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添加自定义页眉。 以下是通过代码生成的自定义报告:

C# 面向对象(对开发者的工作方式):图3 - 从代码示例中生成的自定义PDF,展示了文章中讨论的OOP方法

结论

C# 面向对象(对开发者的工作方式):图4 - IronPDF许可页面

通过理解和应用OOP的基本原则,初学者可以在掌握C#和开发健壮软件解决方案方面迈出重要的一步。 继承和多态使得代码可重复使用和灵活,允许新类在现有结构和功能基础上构建。 抽象和封装确保类仅向外界暴露必要内容,使内部工作保密并免受不当使用。 您可以从liteLicense开始尝试IronPDF免费试用的PDF生成

常见问题解答

我如何在 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 操作定义基类,并通过使用继承和多态扩展它们的特定功能,如添加水印或自定义格式。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。