.NET 帮助

C# 结构体与类(开发人员工作原理)

发布 2024年三月6日
分享:

在 C# 中,结构体和类都是组织和存储数据的基本构件,但它们具有不同的特性,因此适用于不同的场景。了解 C# 结构和类 对于在设计 C# 应用程序时做出明智的决定至关重要。

在本文中,我们将探讨结构体和类之间的主要区别,讨论它们的用例、内存管理和性能影响。此外,我们还将讨论如何将结构体和类与 IronPDF 用于创建 PDF 文件。

1.结构体和类概述

1.1.类别 (参考类型)

引用类型: C# 中的类是驻留在堆上的引用类型,这意味着创建类的实例时,对象的引用会存储在内存中。

堆分配: 类实例在堆内存分配中分配内存,提供了大小的灵活性,并允许代码的不同部分共享对象。

默认构造函数: 类可以有一个默认构造函数,如果没有明确定义,该构造函数会自动提供。

继承: 类支持继承,允许创建具有共享特性的派生类。

using System;
// Define a class
public class MyClass
{
    // Fields (data members)
    public int MyField;
    // Constructor
    public MyClass(int value)
    {
        MyField = value;
    }
    // Method
    public void Display()
    {
        Console.WriteLine($"Value in MyClass: {MyField}");
    }
}
class Program
{
    static void Main()
    {
        // Create an instance of the class
        MyClass myClassInstance = new MyClass(10);
        // Access field and call method
        myClassInstance.Display();
        // Classes are reference types, so myClassInstance refers to the same object in memory
        MyClass anotherInstance = myClassInstance;
        anotherInstance.MyField = 20;
        // Both instances refer to the same object, so the change is reflected in both
        myClassInstance.Display();
        anotherInstance.Display();
    }
}
using System;
// Define a class
public class MyClass
{
    // Fields (data members)
    public int MyField;
    // Constructor
    public MyClass(int value)
    {
        MyField = value;
    }
    // Method
    public void Display()
    {
        Console.WriteLine($"Value in MyClass: {MyField}");
    }
}
class Program
{
    static void Main()
    {
        // Create an instance of the class
        MyClass myClassInstance = new MyClass(10);
        // Access field and call method
        myClassInstance.Display();
        // Classes are reference types, so myClassInstance refers to the same object in memory
        MyClass anotherInstance = myClassInstance;
        anotherInstance.MyField = 20;
        // Both instances refer to the same object, so the change is reflected in both
        myClassInstance.Display();
        anotherInstance.Display();
    }
}
Imports System
' Define a class
Public Class [MyClass]
	' Fields (data members)
	Public MyField As Integer
	' Constructor
	Public Sub New(ByVal value As Integer)
		MyField = value
	End Sub
	' Method
	Public Sub Display()
		Console.WriteLine($"Value in MyClass: {MyField}")
	End Sub
End Class
Friend Class Program
	Shared Sub Main()
		' Create an instance of the class
		Dim myClassInstance As [MyClass] = New [MyClass](10)
		' Access field and call method
		myClassInstance.Display()
		' Classes are reference types, so myClassInstance refers to the same object in memory
		Dim anotherInstance As [MyClass] = myClassInstance
		anotherInstance.MyField = 20
		' Both instances refer to the same object, so the change is reflected in both
		myClassInstance.Display()
		anotherInstance.Display()
	End Sub
End Class
VB   C#

C# 结构与类(开发人员如何使用):图 1 - 前一段代码在控制台中的输出结果

1.2.结构 (价值类型)

值类型: 结构体是值类型,这意味着实际数据存储在变量声明的位置,而不是像基元类型那样存储在内存中的单独位置。这也意味着,如果不使用 Nullable<> 标记使结构体成为可空类型,就不能将空值指定为其值类型。

堆栈分配: 结构体实例在堆栈上分配内存,从而加快了分配和取消分配的速度,但在大小和范围上有所限制。

无默认构造函数: 除非明确定义,否则结构体没有默认构造函数。每个字段都必须在实例化时初始化。

无继承: 结构不支持继承。它们主要用于轻量级数据结构。

using System;
// Define a struct
public struct MyStruct
{
    // Fields (data members)
    public int MyField;
    // Constructor
    public MyStruct(int value)
    {
        MyField = value;
    }
    // Method
    public void Display()
    {
        Console.WriteLine($"Value in MyStruct: {MyField}");
    }
}
class Program
{
    static void Main()
    {
        // Create an instance of the struct
        MyStruct myStructInstance = new MyStruct(10);
        // Access field and call method
        myStructInstance.Display();
        // Structs are value types, so myStructInstance is a copy
        MyStruct anotherInstance = myStructInstance;
        anotherInstance.MyField = 20;
        // Changes to anotherInstance do not affect myStructInstance
        myStructInstance.Display();
        anotherInstance.Display();
    }
}
using System;
// Define a struct
public struct MyStruct
{
    // Fields (data members)
    public int MyField;
    // Constructor
    public MyStruct(int value)
    {
        MyField = value;
    }
    // Method
    public void Display()
    {
        Console.WriteLine($"Value in MyStruct: {MyField}");
    }
}
class Program
{
    static void Main()
    {
        // Create an instance of the struct
        MyStruct myStructInstance = new MyStruct(10);
        // Access field and call method
        myStructInstance.Display();
        // Structs are value types, so myStructInstance is a copy
        MyStruct anotherInstance = myStructInstance;
        anotherInstance.MyField = 20;
        // Changes to anotherInstance do not affect myStructInstance
        myStructInstance.Display();
        anotherInstance.Display();
    }
}
Imports System
' Define a struct
Public Structure MyStruct
	' Fields (data members)
	Public MyField As Integer
	' Constructor
	Public Sub New(ByVal value As Integer)
		MyField = value
	End Sub
	' Method
	Public Sub Display()
		Console.WriteLine($"Value in MyStruct: {MyField}")
	End Sub
End Structure
Friend Class Program
	Shared Sub Main()
		' Create an instance of the struct
		Dim myStructInstance As New MyStruct(10)
		' Access field and call method
		myStructInstance.Display()
		' Structs are value types, so myStructInstance is a copy
		Dim anotherInstance As MyStruct = myStructInstance
		anotherInstance.MyField = 20
		' Changes to anotherInstance do not affect myStructInstance
		myStructInstance.Display()
		anotherInstance.Display()
	End Sub
End Class
VB   C#

C# 结构与类(开发人员如何使用):图 2 - 前一段代码在控制台中的输出结果

2.使用案例和指南

2.1.何时使用类

复杂的状态和行为: 当你需要为具有状态和行为的复杂数据结构建模时,请使用类。类适合表示具有多个属性和方法的复杂对象。

引用语义: 如果你想共享对象的实例,并在代码的不同部分反映变化,类是合适的选择。

2.2.何时使用结构体

简单数据结构: 结构非常适合表示轻量级实体的简单数据结构,如点、矩形、键值对等小型数据结构,或者结构在逻辑上表示单个值,类似于原始类型。

值语义: 当你偏好值语义并希望避免堆分配的开销时,结构体是一个很好的选择。

性能方面的考虑: 在对性能要求较高的情况下,尤其是对小型、频繁使用的对象而言,结构体可以通过堆分配提高效率。

3.内存分配差异

3.1.类别

引用计数: 类实例的内存由垃圾回收器通过引用计数进行管理。当对象不再被引用时,就符合垃圾回收条件。

内存泄漏的可能性: 如果在不再需要对象时没有对其进行正确处理,对引用的不当处理可能会导致内存泄漏。

3.2.结构

无垃圾回收: 结构体不依赖于垃圾回收,因为它们是值类型,管理方式不同。当结构体超出作用域时,它们会被自动卸载。

有限的内存开销: 与类相比,结构体的内存开销较低,因此在内存使用率较高的情况下,结构体非常高效。

4.性能考虑因素

班级

间接访问: 由于类实例是通过引用访问的,因此需要额外的间接层次,这可能会带来轻微的性能开销。

堆分配: 在堆上动态分配内存会导致创建和销毁对象的时间延长。

结构

直接访问: 结构可直接访问,无需额外的间接层。这可以为小型、频繁使用的对象带来更好的性能。

堆栈分配: 内存的堆栈分配可以更快地创建和销毁结构体实例。

5.介绍 IronPDF

IronPDF IronPDF 是一个强大的 C# 库,设计用于在 .NET 应用程序中无缝生成、处理和渲染 PDF。有了 IronPDF,开发人员可以毫不费力地创建、修改 PDF 文档并与之交互,使其成为执行从 HTML 内容动态生成 PDF 到从现有文档中提取数据等任务的重要工具。这个多功能库简化了与 PDF 相关的功能,为开发 Web 应用程序、桌面软件或任何需要高效处理 PDF 的 .NET 项目的开发人员提供了一套全面的功能。

5.1.安装 IronPDF

在深入学习代码示例之前,您需要安装 IronPDF。您可以使用 NuGet 包管理器控制台或在项目中添加对 IronPDF 库的引用来完成安装。以下步骤概述了安装过程:

  1. NuGet软件包管理器控制台:
    :ProductInstall
  1. 软件包管理器用户界面: 在 NuGet 软件包管理器用户界面中搜索 "IronPDF "并安装最新版本。

安装好 IronPDF 后,您就可以在 C# 应用程序中利用其功能处理 PDF 文件了。

5.2.在 IronPDF 中使用结构体和类

using IronPdf;
using System;
// Sample class
class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}
// Sample struct
struct Point
{
    public int X { get; set; }
    public int Y { get; set; }
}
class Program
{
    static void Main()
    {
        // Sample instances of class and struct
        Person person = new Person { Name = "John Doe", Age = 30 };
        Point point = new Point { X = 10, Y = 20 };
        // Create a new PDF document
        var renderer = new ChromePdfRenderer();
        // Add content with information from class and struct
        string content = $@"<!DOCTYPE html>
                            <html>
                            <body>
                                <h1>Information in IronPDF</h1>
                                <p>Name: {person.Name}</p>
                                <p>Age: {person.Age}</p>
                                <p>Point X: {point.X}</p>
                                <p>Point Y: {point.Y}</p>
                            </body>
                            </html>";
        // Render HTML content to PDF
        var pdf = renderer.RenderHtmlAsPdf(content);
        // Save the PDF to a file
        pdf.SaveAs("InformationDocument.pdf");
    }
}
using IronPdf;
using System;
// Sample class
class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}
// Sample struct
struct Point
{
    public int X { get; set; }
    public int Y { get; set; }
}
class Program
{
    static void Main()
    {
        // Sample instances of class and struct
        Person person = new Person { Name = "John Doe", Age = 30 };
        Point point = new Point { X = 10, Y = 20 };
        // Create a new PDF document
        var renderer = new ChromePdfRenderer();
        // Add content with information from class and struct
        string content = $@"<!DOCTYPE html>
                            <html>
                            <body>
                                <h1>Information in IronPDF</h1>
                                <p>Name: {person.Name}</p>
                                <p>Age: {person.Age}</p>
                                <p>Point X: {point.X}</p>
                                <p>Point Y: {point.Y}</p>
                            </body>
                            </html>";
        // Render HTML content to PDF
        var pdf = renderer.RenderHtmlAsPdf(content);
        // Save the PDF to a file
        pdf.SaveAs("InformationDocument.pdf");
    }
}
Imports IronPdf
Imports System
' Sample class
Friend Class Person
	Public Property Name() As String
	Public Property Age() As Integer
End Class
' Sample struct
Friend Structure Point
	Public Property X() As Integer
	Public Property Y() As Integer
End Structure
Friend Class Program
	Shared Sub Main()
		' Sample instances of class and struct
		Dim person As New Person With {
			.Name = "John Doe",
			.Age = 30
		}
		Dim point As New Point With {
			.X = 10,
			.Y = 20
		}
		' Create a new PDF document
		Dim renderer = New ChromePdfRenderer()
		' Add content with information from class and struct
		Dim content As String = $"<!DOCTYPE html>
                            <html>
                            <body>
                                <h1>Information in IronPDF</h1>
                                <p>Name: {person.Name}</p>
                                <p>Age: {person.Age}</p>
                                <p>Point X: {point.X}</p>
                                <p>Point Y: {point.Y}</p>
                            </body>
                            </html>"
		' Render HTML content to PDF
		Dim pdf = renderer.RenderHtmlAsPdf(content)
		' Save the PDF to a file
		pdf.SaveAs("InformationDocument.pdf")
	End Sub
End Class
VB   C#
  • Person 是一个示例类,代表一个具有 NameAge 属性的人。
  • 是一个示例结构,表示二维坐标系中的一个点,具有XY属性。
  • 我们将创建 Person 类和 Point 结构的实例。
  • 然后,HTML 内容被渲染到 PDF 文档中,并保存为 "InformationDocument.pdf"。

5.2.1.输出 PDF 文件

C# 结构与类(开发人员如何使用):图 3 - 前面代码输出的 PDF 文件

6.结论

总之,选择使用 C# 结构还是类取决于应用程序的具体要求和特点。类作为引用类型,适合于对具有状态和行为的复杂实体建模,支持继承,并便于共享实例。另一方面,结构体作为值类型,是具有值语义的轻量级数据结构的理想选择,在堆栈分配和直接访问方面具有性能优势。

IronPDF 提供了 免费试用许可证 用户了解 IronPDF 特性和功能的好机会。要了解有关 IronPDF 的更多信息,请访问以下网站 链接 使用 IronPDF 创建 PDF 文件的详细教程可从以下网址获取 链接.

< 前一页
C# 初始化数组(开发人员如何使用)
下一步 >
NPlot C#(开发者工作原理)

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

免费NuGet下载 总下载量: 10,731,156 查看许可证 >