.NET 帮助

C# 常量(开发人员如何使用)

发布 2024年三月6日
分享:

在 C# 中,一个 const 关键字 是一种强大的工具,用于定义常量字段或在编译时已知的值。这些值是不可变的,也就是说,一旦它们被设置,其值在整个程序中都不会改变。使用const可以清楚地指明要保持不变的值,从而提高代码的可读性和可维护性。在本文中,我们将讨论 const 关键字和 IronPDF 库.

声明常量变量

要声明一个常量变量,可以使用 const 关键字,后面跟一个数据类型,然后立即对其进行初始化。例如,const int myConstValue = 100; 定义了一个整数常量。值得注意的是,常量变量必须在声明时进行初始化,因为其值是在编译时确定的,并在程序运行前进行完全评估。

public class Program
{
    public const int MaxSize = 10;
    static void Main(string [] args)
    {
        Console.WriteLine(MaxSize);
    }
}
public class Program
{
    public const int MaxSize = 10;
    static void Main(string [] args)
    {
        Console.WriteLine(MaxSize);
    }
}
Public Class Program
	Public Const MaxSize As Integer = 10
	Shared Sub Main(ByVal args() As String)
		Console.WriteLine(MaxSize)
	End Sub
End Class
VB   C#

C# Const(如何为开发人员工作):图 1 - Const 输出

本例说明了常量整数的一个简单用法 (const int) 常量。在同一个类中可以访问 MaxSize 常量,并可在 static void Main 方法中直接使用。

常变量与只读变量

虽然constreadonly关键字都用于声明不可变值,但它们之间有重要的区别。const 字段是编译时常量,这意味着它的值在编译时就已确定,并直接嵌入到中间语言中 (IL) 代码。这使得它成为静态代码,无法修改。

另一方面,只读变量可以在声明时分配,也可以在类的构造函数中分配。这样就有了一定的灵活性,因为只读字段可以根据类实例化时使用的构造函数而具有不同的值。

public class Program
{
    public const string ConstExample = "Constant"; // const string
    public readonly string ReadonlyExample;
    public Program()
    {
        ReadonlyExample = "Initialized at runtime";
    }
    static void Main(string [] args)
    {
        Program p = new Program();
        Console.WriteLine(ConstExample);
        Console.WriteLine(p.ReadonlyExample);
    }
}
public class Program
{
    public const string ConstExample = "Constant"; // const string
    public readonly string ReadonlyExample;
    public Program()
    {
        ReadonlyExample = "Initialized at runtime";
    }
    static void Main(string [] args)
    {
        Program p = new Program();
        Console.WriteLine(ConstExample);
        Console.WriteLine(p.ReadonlyExample);
    }
}
Public Class Program
	Public Const ConstExample As String = "Constant" ' const string
	Public ReadOnly ReadonlyExample As String
	Public Sub New()
		ReadonlyExample = "Initialized at runtime"
	End Sub
	Shared Sub Main(ByVal args() As String)
		Dim p As New Program()
		Console.WriteLine(ConstExample)
		Console.WriteLine(p.ReadonlyExample)
	End Sub
End Class
VB   C#

C# Const(如何为开发人员工作):图 2 - 只读字段输出

常量变量的范围

常量变量可以在方法中声明,也可以作为类的成员声明。在方法中声明的常量变量称为局部常量。局部常量只能在其声明的方法中访问。

public class Program
{
    static void DemoMethod()
    {
        const int LocalConst = 5; // local constant
        Console.WriteLine(LocalConst);
    }
}
public class Program
{
    static void DemoMethod()
    {
        const int LocalConst = 5; // local constant
        Console.WriteLine(LocalConst);
    }
}
Public Class Program
	Private Shared Sub DemoMethod()
		Const LocalConst As Integer = 5 ' local constant
		Console.WriteLine(LocalConst)
	End Sub
End Class
VB   C#

C# 常量(如何为开发人员工作):图 3 - 本地常量输出

相反,当const在类中声明但不在任何方法中时,由于const字段是隐式静态的,因此可以通过同类的任何静态函数访问它。不过,如果不通过类名引用const字段,而试图从实例方法中访问该const字段,则会导致编译错误。

编译时间与运行时间常量对比

const 值的主要特点是在编译时进行评估。这就意味着const字段的值必须是编译器已知并完全评估过的。这与在运行时求值的变量形成鲜明对比,后者的值是在程序执行过程中确定的。

例如,如果试图根据运行时进行的计算为const字段赋值,就会导致编译时错误。编译器要求根据常量表达式或编译时已知的字面值为 const 赋值。

const double Pi = Math.PI; // This will cause a compile time error
const double Pi = Math.PI; // This will cause a compile time error
Const Pi As Double = Math.PI ' This will cause a compile time error
VB   C#

C&num 中常量和静态成员的高级使用;

除了 C# 中constreadonly的基础知识外,了解如何使用常量表达式、静态构造函数和静态字段可以提升您的编码实践,尤其是在处理需要在类的实例间共享的常量值时。

常量表达式

C# 中的常量表达式是一种可以在编译时完全求值的表达式。因此,当您声明一个 const 变量时,其声明的右侧必须是一个常量表达式。这就确保了 const 值是固定的,可以直接嵌入编译后的代码中,从而实现高度优化和高效的应用程序。

public class Calculator
{
    public const int Multiplier = 2;
    public const int DoubleMultiplier = Multiplier * 2; // Constant expression
}
public class Calculator
{
    public const int Multiplier = 2;
    public const int DoubleMultiplier = Multiplier * 2; // Constant expression
}
Public Class Calculator
	Public Const Multiplier As Integer = 2
	Public Const DoubleMultiplier As Integer = Multiplier * 2 ' Constant expression
End Class
VB   C#

在本例中,DoubleMultiplier 是一个常量表达式,因为它是用另一个常量值计算出来的,因此有资格成为编译时常量。

静态构造函数

C# 中的静态构造函数是一种特殊的构造函数,用于初始化类的静态字段。在创建第一个实例或引用任何静态成员之前,它会被自动调用。静态构造函数适用于复杂的静态数据初始化,或执行需要在每个类型而不是每个实例中执行一次的操作。

public class Program
{
    public static readonly string StartTime;
    static Program()
    {
        StartTime = DateTime.Now.ToString("T");
    }
    public static void DisplayStartTime()
    {
        Console.WriteLine($"Program started at: {StartTime}");
    }
}
public class Program
{
    public static readonly string StartTime;
    static Program()
    {
        StartTime = DateTime.Now.ToString("T");
    }
    public static void DisplayStartTime()
    {
        Console.WriteLine($"Program started at: {StartTime}");
    }
}
Public Class Program
	Public Shared ReadOnly StartTime As String
	Shared Sub New()
		StartTime = DateTime.Now.ToString("T")
	End Sub
	Public Shared Sub DisplayStartTime()
		Console.WriteLine($"Program started at: {StartTime}")
	End Sub
End Class
VB   C#

静态构造函数用当前时间初始化StartTime字段。然后可通过 DisplayStartTime 静态方法访问该值,这展示了静态构造函数如何用于初始化只读字段,并使用运行前未知的值。

静态字段以及只读和静态关键字

静态字段属于类而不是类的任何实例,使用 static 关键字进行声明。与readonly关键字结合使用时,静态字段可以在声明时或在静态构造函数中初始化,之后不能修改。

public class Configuration
{
    public static readonly int MaxUsers;
    public const int TimeoutSeconds = 30;
    static Configuration()
    {
        MaxUsers = FetchMaxUsersFromConfig();
    }
    private static int FetchMaxUsersFromConfig()
    {
        // Imagine this method reads from a configuration file
        return 100;
    }
}
public class Configuration
{
    public static readonly int MaxUsers;
    public const int TimeoutSeconds = 30;
    static Configuration()
    {
        MaxUsers = FetchMaxUsersFromConfig();
    }
    private static int FetchMaxUsersFromConfig()
    {
        // Imagine this method reads from a configuration file
        return 100;
    }
}
Public Class Configuration
	Public Shared ReadOnly MaxUsers As Integer
	Public Const TimeoutSeconds As Integer = 30
	Shared Sub New()
		MaxUsers = FetchMaxUsersFromConfig()
	End Sub
	Private Shared Function FetchMaxUsersFromConfig() As Integer
		' Imagine this method reads from a configuration file
		Return 100
	End Function
End Class
VB   C#

本例演示了如何使用静态构造函数来初始化静态字段MaxUsers只读值,该值可在运行时获取,也可能是从配置文件中获取。const 字段 TimeoutSeconds** 表示直接嵌入代码的编译时常量。

IronPDF 简介

C# Const(如何为开发人员工作):图 4 - IronPDF

IronPDF 是一个多功能库,能让开发人员在 .NET 应用程序中创建、编辑和读取 PDF 文档。这个功能强大的工具简化了 PDF 的生成,允许开发人员 将 HTML 转换为 PDF、 操控内容,轻松从PDF文件中提取数据。

IronPDF的强大之处在于转换 HTML 转 PDF, 保持布局和样式。它是从网页内容生成PDF的理想工具,例如报告、发票和文档。HTML文件、URL和HTML字符串可以轻松转换为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");
    }
}
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
VB   C#

IronPDF入门和常例

为了演示如何将 IronPDF 集成到 .NET 项目中,让我们来看一个简单的示例:我们使用一个常量来定义要转换为 PDF 文档的 HTML 字符串。

using IronPdf;
public class PdfGenerator
{
    // Defining a constant HTML template
    public const string HtmlTemplate = @"
        <html>
            <head>
                <title>PDF Report</title>
            </head>
            <body>
                <h1>IronPDF Report</h1>
                <p>This is a simple PDF document generated from HTML string using IronPDF.</p>
            </body>
        </html>";
    public static void CreatePdf(string filePath)
    {
        IronPdf.License.LicenseKey = "License";
        // Create a new PDF document from HTML template
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf(HtmlTemplate);
        // Save the PDF document to a file
        pdf.SaveAs(filePath);
        Console.WriteLine($"PDF generated successfully at {filePath}");
    }
}
class Program
{
    static void Main(string [] args)
    {
        PdfGenerator.CreatePdf("example.pdf");
    }
}
using IronPdf;
public class PdfGenerator
{
    // Defining a constant HTML template
    public const string HtmlTemplate = @"
        <html>
            <head>
                <title>PDF Report</title>
            </head>
            <body>
                <h1>IronPDF Report</h1>
                <p>This is a simple PDF document generated from HTML string using IronPDF.</p>
            </body>
        </html>";
    public static void CreatePdf(string filePath)
    {
        IronPdf.License.LicenseKey = "License";
        // Create a new PDF document from HTML template
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf(HtmlTemplate);
        // Save the PDF document to a file
        pdf.SaveAs(filePath);
        Console.WriteLine($"PDF generated successfully at {filePath}");
    }
}
class Program
{
    static void Main(string [] args)
    {
        PdfGenerator.CreatePdf("example.pdf");
    }
}
Imports IronPdf
Public Class PdfGenerator
	' Defining a constant HTML template
	Public Const HtmlTemplate As String = "
        <html>
            <head>
                <title>PDF Report</title>
            </head>
            <body>
                <h1>IronPDF Report</h1>
                <p>This is a simple PDF document generated from HTML string using IronPDF.</p>
            </body>
        </html>"
	Public Shared Sub CreatePdf(ByVal filePath As String)
		IronPdf.License.LicenseKey = "License"
		' Create a new PDF document from HTML template
		Dim renderer = New ChromePdfRenderer()
		Dim pdf = renderer.RenderHtmlAsPdf(HtmlTemplate)
		' Save the PDF document to a file
		pdf.SaveAs(filePath)
		Console.WriteLine($"PDF generated successfully at {filePath}")
	End Sub
End Class
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		PdfGenerator.CreatePdf("example.pdf")
	End Sub
End Class
VB   C#

在本例中,HtmlTemplate 常量定义了简单的 HTML 内容,作为 PDF 文档的源文件。CreatePdf 方法利用 IronPDF 的 ChromePdfRenderer 类将 HTML 转换为 PDF,并将其保存到指定的文件路径。这展示了 IronPDF 如何利用const关键字定义不可变的 HTML 模板,轻松地从静态 HTML 内容生成 PDF。

输出

这是输出的 PDF 文件:

C# Const(如何为开发人员工作):图 5 - PDF 输出

结论

C# Const(如何为开发人员工作):图 6 - 许可证

在 C# 中,const 关键字是定义编译时已知的不可变值的重要功能。它可以清楚地指明哪些值是常量,有助于提高代码的可读性和可维护性。请记住,const 变量是隐式静态变量,必须在声明时初始化,其值必须是编译时常量。相比之下,readonly 变量提供了更大的灵活性,但要在运行时初始化。

IronPDF 的突出之处不仅在于其强大的 PDF 操作功能,还在于其灵活的采用模式。对于希望探索其功能的开发人员和组织机构,IronPDF 提供了一个 免费试用这为评估其功能和集成便利性提供了绝佳机会,而无需初始投资。

当准备将 IronPDF 用于商业用途时,许可选项从 $749开始。这种定价结构旨在满足不同项目规模和类型的需求,确保您可以选择最适合您的开发和发布计划的许可证。

< 前一页
C# 线程睡眠方法(开发人员如何使用)
下一步 >
RabbitMQ C#(开发人员如何使用)

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

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