跳至页脚内容
.NET 帮助

C# 枚举(开发人员如何使用)

正文内容: 枚举是枚举的简写,是一种强大的特性,使开发者能够建立一组命名的常量。 这些常量通过为值提供有意义的名称,使代码更具可读性和可维护性。 在本文中,我们将通过各种示例和解释探讨C#中枚举的基础和高级概念。 我们的目标是提供对枚举的全面理解,以及如何在您的C#应用程序中有效地使用它们,使用.NET中的IronPDF库生成PDF

C#中的枚举简介

枚举是C#中的一种值类型,使变量可以是一组预定义常量,每个常量都被称为枚举成员。 使用enum关键字声明一个枚举类型,提供了一种将常量值分组到一个名称下的方法。 枚举提高了代码的可读性,并减少了由于传递错误值而导致的错误。

// Define an enum with four members
enum Season { Spring, Summer, Autumn, Winter }
// Define an enum with four members
enum Season { Spring, Summer, Autumn, Winter }
' Define an enum with four members
Friend Enum Season
	Spring
	Summer
	Autumn
	Winter
End Enum
$vbLabelText   $csharpLabel

在上面的代码中,Season是一个枚举类型,具有四个成员:春季、夏季、秋季和冬季。 通过定义这个枚举,我们现在可以创建Season类型的变量,这些变量只能保存这四个值中的一个。

枚举的基础类型

理解枚举成员的整数值

默认情况下,C#中枚举的基础类型是int,被称为基础整型类型,枚举成员的整数值从0开始。每个成员的整数值在前一个成员的基础上增加1,除非明确指定。 您也可以将枚举的基础类型定义为其他整型类型。

// Define an enum with a byte underlying type and specific values
enum Season : byte { Spring = 1, Summer, Autumn = 4, Winter }
// Define an enum with a byte underlying type and specific values
enum Season : byte { Spring = 1, Summer, Autumn = 4, Winter }
' Define an enum with a byte underlying type and specific values
Friend Enum Season As Byte
	Spring = 1
	Summer
	Autumn = 4
	Winter
End Enum
$vbLabelText   $csharpLabel

在这个例子中,Season枚举的基础类型是字节。 Spring被显式分配了一个值1,使其成为默认值,而夏季、秋季和冬季则根据它们的顺序分配相应的值。

在您的代码中使用枚举

要使用枚举,只需声明一个指定枚举类型的变量,并为其分配一个枚举值,例如在枚举声明中定义的不同值之一,使用点语法。

// Declare a Season variable and assign it an enum member value
Season currentSeason = Season.Autumn;
// Declare a Season variable and assign it an enum member value
Season currentSeason = Season.Autumn;
' Declare a Season variable and assign it an enum member value
Dim currentSeason As Season = Season.Autumn
$vbLabelText   $csharpLabel

这一行创建了一个Season类型的变量currentSeason,并将其赋值为Autumn。 这明确表示currentSeason只能保存有效的Season值。

在枚举值和整数之间转换

您可以通过强制转换将枚举值转换为其对应的整数值,反之亦然。 当需要以数字形式存储或传输数据时,这非常有用。

// Convert Season.Autumn to its integer value and vice versa
int autumnInt = (int)Season.Autumn;     // autumnInt will be 4
Season season = (Season)4;              // season will be Season.Autumn
// Convert Season.Autumn to its integer value and vice versa
int autumnInt = (int)Season.Autumn;     // autumnInt will be 4
Season season = (Season)4;              // season will be Season.Autumn
Imports System

' Convert Season.Autumn to its integer value and vice versa
Dim autumnInt As Integer = CInt(Math.Truncate(Season.Autumn)) ' autumnInt will be 4
Dim season As Season = CType(4, Season) ' season will be Season.Autumn
$vbLabelText   $csharpLabel

在这里,autumnInt的值为4,这对应于Season枚举中的Autumn。 反之,当将整数4转换回Season时,season将被设置为Autumn

与枚举方法配合使用

C#提供了几种用于操作枚举的方法,比如Enum.GetName(), Enum.GetNames(), Enum.GetValue()Enum.GetValues(),对于访问与每个枚举成员关联的整数常量非常有用。

// Get names of all enum members and print them
string[] names = Enum.GetNames(typeof(Season));
foreach (string name in names)
{
    Console.WriteLine(name);
}
// Get names of all enum members and print them
string[] names = Enum.GetNames(typeof(Season));
foreach (string name in names)
{
    Console.WriteLine(name);
}
' Get names of all enum members and print them
Dim names() As String = System.Enum.GetNames(GetType(Season))
For Each name As String In names
	Console.WriteLine(name)
Next name
$vbLabelText   $csharpLabel

C#枚举(对开发人员的工作原理):图1 - 与Season枚举关联的每个值的控制台输出

该代码片段打印出Season枚举的所有成员名称。 这些方法在迭代枚举的所有可能值或在字符串表示和枚举值之间转换时非常有用。

为枚举成员指定特定的值

您可以为枚举成员分配特定的整数值,以明确控制其数值。

// Define an enum with custom integer values for members
enum ErrorCode : int { None = 0, NotFound = 404, Unauthorized = 401 }
// Define an enum with custom integer values for members
enum ErrorCode : int { None = 0, NotFound = 404, Unauthorized = 401 }
' Define an enum with custom integer values for members
Friend Enum ErrorCode As Integer
	None = 0
	NotFound = 404
	Unauthorized = 401
End Enum
$vbLabelText   $csharpLabel

在这个例子中,ErrorCode是一个枚举,每个成员都分配了自定义的整数值。 这对于预定义的数字代码非常有用,例如HTTP状态代码。

将枚举用作比特标志

通过使用[Flags]属性,您可以将枚举定义为一组比特标志。 这允许您在单个枚举变量中存储多个值的组合。

[Flags]
// Define an enum for permissions using bit flags
enum Permissions { None = 0, Read = 1, Write = 2, Execute = 4 }
[Flags]
// Define an enum for permissions using bit flags
enum Permissions { None = 0, Read = 1, Write = 2, Execute = 4 }
' Define an enum for permissions using bit flags
<Flags>
Friend Enum Permissions
	None = 0
	Read = 1
	Write = 2
	Execute = 4
End Enum
$vbLabelText   $csharpLabel

使用上面定义的Permissions枚举,您可以使用按位或运算符组合不同的权限。

// Combine permissions using bitwise OR
Permissions myPermissions = Permissions.Read | Permissions.Write;
// Combine permissions using bitwise OR
Permissions myPermissions = Permissions.Read | Permissions.Write;
' Combine permissions using bitwise OR
Dim myPermissions As Permissions = Permissions.Read Or Permissions.Write
$vbLabelText   $csharpLabel

这将myPermissions设置为ReadWrite权限的组合。

枚举和Switch语句

枚举与switch语句效果极佳,使您能够根据枚举的值执行不同的代码块。

// Use a switch statement with an enum
Season season = Season.Summer;
switch (season)
{
    case Season.Spring:
        Console.WriteLine("It's spring.");
        break;
    case Season.Summer:
        Console.WriteLine("It's summer.");
        break;
    case Season.Autumn:
        Console.WriteLine("It's autumn.");
        break;
    case Season.Winter:
        Console.WriteLine("It's winter.");
        break;
}
// Use a switch statement with an enum
Season season = Season.Summer;
switch (season)
{
    case Season.Spring:
        Console.WriteLine("It's spring.");
        break;
    case Season.Summer:
        Console.WriteLine("It's summer.");
        break;
    case Season.Autumn:
        Console.WriteLine("It's autumn.");
        break;
    case Season.Winter:
        Console.WriteLine("It's winter.");
        break;
}
' Use a switch statement with an enum
Dim season As Season = Season.Summer
Select Case season
	Case Season.Spring
		Console.WriteLine("It's spring.")
	Case Season.Summer
		Console.WriteLine("It's summer.")
	Case Season.Autumn
		Console.WriteLine("It's autumn.")
	Case Season.Winter
		Console.WriteLine("It's winter.")
End Select
$vbLabelText   $csharpLabel

这段代码将打印“现在是夏季。”因为season变量设置为Season.Summer

解析字符串到枚举

C#允许您通过Enum.Parse()方法解析字符串以获取对应的枚举值。

// Parse a string into an enum value
string input = "Winter";
Season season = (Season)Enum.Parse(typeof(Season), input);
// Parse a string into an enum value
string input = "Winter";
Season season = (Season)Enum.Parse(typeof(Season), input);
' Parse a string into an enum value
Dim input As String = "Winter"
Dim season As Season = DirectCast(System.Enum.Parse(GetType(Season), input), Season)
$vbLabelText   $csharpLabel

这段代码将字符串"Winter"转换为其对应的枚举值Season.Winter

将IronPDF与C#枚举结合

IronPDF PDF Library for Dynamic Document Generation是一个用于.NET应用程序的PDF库,帮助开发者轻松创建、编辑和操作PDF文档。 此强大的库在需要动态生成PDF的场景中特别有用,例如生成报告或发票。 在这一部分,我们将探讨如何将IronPDF与C#枚举集成,用于在.NET中从HTML创建PDF报告,同时还会介绍如何在您的项目中安装IronPDF。

使用IronPDF,您可以将任何HTML、URL或网页转换为与源相同外观的PDF。 这是生成发票、报告和其他基于网络的内容PDF的一个很好的选择。 准备好将HTML转换为PDF了吗? IronPDF使其变得轻而易举。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

安装 IronPDF。

使用NuGet包管理器控制台安装IronPDF非常简单。 在Visual Studio中打开包管理器控制台,写入以下命令:

Install-Package IronPdf

此命令将在我们的项目中安装IronPDF。

另一种方式是利用Visual Studio在您的项目中安装IronPDF。 在Visual Studio中,右键点击解决方案资源管理器,然后点击“NuGet包管理器”(适用于解决方案)。 之后,点击左侧的浏览选项卡。然后搜索IronPDF,点击安装,并将其添加到您的项目中。

C#枚举(对开发人员的工作原理):图2 - 使用NuGet包管理器搜索IronPDF安装IronPDF

使用IronPDF和枚举

让我们考虑一个您想要生成一个包含季节性销售数据报告的PDF文档的场景。 您可以使用枚举表示不同的季节,并使用IronPDF生成PDF报告。 首先,定义一个用于季节的枚举:

public enum Season
{
    Spring,
    Summer,
    Autumn,
    Winter
}
public enum Season
{
    Spring,
    Summer,
    Autumn,
    Winter
}
Public Enum Season
	Spring
	Summer
	Autumn
	Winter
End Enum
$vbLabelText   $csharpLabel

接下来,我们将编写一个方法,基于所选的季节生成PDF报告。 此方法将利用IronPDF以创建一个简单的PDF文档,概述给定季节的销售数据。

using IronPdf;
public class SalesReportGenerator
{
    public static void GenerateSeasonalSalesReport(Season season)
    {
        IronPdf.License.LicenseKey = "License-Key";
        var Renderer = new IronPdf.ChromePdfRenderer();
        var htmlTemplate = $"<h1>Sales Report for {season}</h1><p>This section contains sales data for the {season} season.</p>";
        var pdf = Renderer.RenderHtmlAsPdf(htmlTemplate);
        var outputPath = $@"{season}SalesReport.pdf";
        pdf.SaveAs(outputPath);
        Console.WriteLine($"PDF report generated: {outputPath}");
    }
}
using IronPdf;
public class SalesReportGenerator
{
    public static void GenerateSeasonalSalesReport(Season season)
    {
        IronPdf.License.LicenseKey = "License-Key";
        var Renderer = new IronPdf.ChromePdfRenderer();
        var htmlTemplate = $"<h1>Sales Report for {season}</h1><p>This section contains sales data for the {season} season.</p>";
        var pdf = Renderer.RenderHtmlAsPdf(htmlTemplate);
        var outputPath = $@"{season}SalesReport.pdf";
        pdf.SaveAs(outputPath);
        Console.WriteLine($"PDF report generated: {outputPath}");
    }
}
Imports IronPdf
Public Class SalesReportGenerator
	Public Shared Sub GenerateSeasonalSalesReport(ByVal season As Season)
		IronPdf.License.LicenseKey = "License-Key"
		Dim Renderer = New IronPdf.ChromePdfRenderer()
		Dim htmlTemplate = $"<h1>Sales Report for {season}</h1><p>This section contains sales data for the {season} season.</p>"
		Dim pdf = Renderer.RenderHtmlAsPdf(htmlTemplate)
		Dim outputPath = $"{season}SalesReport.pdf"
		pdf.SaveAs(outputPath)
		Console.WriteLine($"PDF report generated: {outputPath}")
	End Sub
End Class
$vbLabelText   $csharpLabel

在这个例子中,我们定义了一个方法GenerateSeasonalSalesReport,它使用Season枚举作为参数。 它使用IronPDF的ChromePdfRenderer类从包含季节名称和销售数据占位符文本的HTML字符串生成PDF。 然后,以包含季节名称的文件名形式保存PDF。

执行

要生成季节性销售报告,请以特定季节调用GenerateSeasonalSalesReport方法:

static void Main(string[] args)
{
    SalesReportGenerator.GenerateSeasonalSalesReport(Season.Winter);
}
static void Main(string[] args)
{
    SalesReportGenerator.GenerateSeasonalSalesReport(Season.Winter);
}
Shared Sub Main(ByVal args() As String)
	SalesReportGenerator.GenerateSeasonalSalesReport(Season.Winter)
End Sub
$vbLabelText   $csharpLabel

此调用生成一个名为WinterSalesReport.pdf的PDF文档,其中包含冬季的销售报告。

C#枚举(对开发人员的工作原理):图3 - 使用IronPDF生成的代码示例PDF输出

结论

C#中的枚举提供了一种类型安全的方式来处理相关命名常量的集合。 它们增强了代码的可读性,减少了错误,并促进了代码组织的简洁性。 通过将相关常量值分组到一个有意义的名称下,枚举使您的代码更易于理解和维护。

将IronPDF与C#中的枚举结合,允许基于枚举类型动态生成PDF文档。IronPDF提供了一免费试用版,其综合PDF工具,为不同项目需求和规模提供了一系列选项。

常见问题解答

C# 中的枚举是什么,它们为什么有用?

枚举,简称为枚举类型,是 C# 中的一项特性,它允许开发人员定义一组命名常量。这样可以提高代码的可读性和维护性,因为它将常量值归为一个名称下。

如何在 C# 中声明和初始化一个枚举?

在 C# 中,您可以使用enum关键字后跟枚举名称及其成员来声明一个枚举。例如,enum Season { Spring, Summer, Autumn, Winter }创建了一个名为 Season 的枚举,具有四个成员。

C# 中的枚举成员可以拥有自定义的基础值吗?

是的,您可以为 C# 中的枚举成员分配特定的整数值,从而控制它们的数字表示。例如,enum ErrorCode { None = 0, NotFound = 404, Unauthorized = 401 }为每个成员分配了自定义值。

如何在 C# 中将枚举值转换为整数及相反的转换?

要将枚举值转换为整数,可以使用类型转换,例如(int)Season.Autumn。要将整数转换为枚举,请将整数类型转换为枚举类型,如(Season)4

C# 中 [Flags] 属性在枚举中的用途是什么?

C# 中的 [Flags] 属性允许枚举作为一组位标志使用,允许在单个变量中组合多个值。这在需要表示多个值的场景中很有用,例如组合『读』和『写』权限。

如何利用枚举生成 C# 中的动态 PDF 文档?

枚举可以用来表示动态 PDF 文档生成中的不同类别或类型。例如,可以使用『Season』枚举为季节性销售报告创建 PDF,通过选择适当的枚举值动态调整内容。

在 C# 项目中安装用于 PDF 生成的库的过程是怎样的?

要在 C# 项目中安装 PDF 生成库,可以使用 NuGet 包管理器控制台,使用诸如Install-Package [LibraryName]之类的命令,或使用 Visual Studio 的 NuGet 包管理器界面进行安装。

如何在 C# 中实现使用 switch 语句的枚举?

可以使用枚举与 switch 语句一起使用,根据枚举的值执行不同的代码块。例如,对『Season』枚举变量的 switch 语句可以为每个季节执行特定的逻辑,增强代码的清晰度和组织性。

如何在 C# 中将字符串解析为枚举?

要在 C# 中将字符串解析为枚举值,可以使用Enum.Parse()方法。例如,Enum.Parse(typeof(Season), "Winter")将字符串 'Winter' 转换为其对应的枚举值 'Season.Winter'。

可用于处理 C# 中枚举名称的方法有哪些?

C# 提供了Enum.GetName()Enum.GetNames()等方法来处理枚举名称。Enum.GetName()返回具有指定值的常量名称,而Enum.GetNames()返回枚举中所有常量名称的数组。

Curtis Chau
技术作家

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

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