跳過到頁腳內容
.NET幫助

C# 常量(對於開發者的運行原理)

在 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
$vbLabelText   $csharpLabel

C# Const (How It Works For Developers):圖 1 - Const 輸出

本範例說明了常數整數 (const int) 在類別中的簡單使用。 MaxSize 常數可在相同的類別中存取,並可直接在 static void Main 方法中使用。

const 變數 vs. 只讀變數

雖然 constreadonly 兩個關鍵字都用來宣告不可變的值,但它們之間有重要的差異。 const 欄位是編譯時常數,意即其值在編譯時確定,並直接嵌入到中級語言 (IL) 程式碼中。 這使其成為靜態,無法修改。

另一方面,只讀變數可以在宣告時或類別的建構器內指定。 這允許了一些彈性,因為 readonly 欄位可以有不同的值,這取決於用來實體化類別的建構器。

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
$vbLabelText   $csharpLabel

C# Const (How It Works For Developers):圖 2 - 只讀欄位輸出

常數變數的範圍

常變數可以在方法中宣告,也可以作為類別的成員。 當您在一個方法中宣告一個 const 變數時,它被稱為局部常數。 局部常量只能在其宣告的方法中存取。

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
$vbLabelText   $csharpLabel

C# Const (How It Works For Developers):圖 3 - 局部常數輸出

相反地,當 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
$vbLabelText   $csharpLabel

C# 中常數和靜態成員的進階使用;

除了 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
$vbLabelText   $csharpLabel

在這個範例中,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
$vbLabelText   $csharpLabel

靜態構建程式會以目前的時間初始化 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
$vbLabelText   $csharpLabel

本範例示範使用靜態的建構器來初始化 readonly 靜態欄位 MaxUsers,其值會在執行時擷取,可能來自配置檔案。const 欄位 TimeoutSeconds代表直接嵌入程式碼的編譯時常數。

IronPDF 簡介

C# Const (How It Works For Developers):圖 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
$vbLabelText   $csharpLabel

開始使用 IronPDF 和 const 範例

為了展示 IronPDF for .NET 如何整合到 .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
$vbLabelText   $csharpLabel

在這個範例中,HtmlTemplate 常數定義了簡單的 HTML 內容,作為我們 PDF 文件的來源。 CreatePdf 方法利用 IronPDF 的 ChromePdfRenderer 類將此 HTML 轉換為 PDF,並將其儲存至指定的檔案路徑。 這展示了 IronPDF 可以輕鬆地利用 const 關鍵字來定義不可變的 HTML 模板,從靜態 HTML 內容產生 PDF。

輸出

以下是輸出的 PDF 檔案:

C# Const (How It Works For Developers):圖 5 - PDF 輸出

結論

C# Const (How It Works For Developers):圖 6 - 授權

在 C# 中,const 關鍵字是定義在編譯時已知的不可變值的重要功能。它可以清楚地指出哪些值是常量,有助於改善程式碼的可讀性和可維護性。 請記住,const 變數是隱含的靜態變數,必須在宣告時初始化,而且其值必須是編譯時常數。 相較之下,readonly 變數提供更多的彈性,但會在執行時初始化。

IronPDF 的突出之處不僅在於其在 PDF 處理方面的強大功能,還在於其靈活的採用模式。 對於想要探索其功能的開發人員和組織,IronPDF 提供 免費試用,提供一個絕佳的機會,讓您無需初始投資即可評估其功能和整合難易度。

當準備使用 IronPDF 作商業用途時,授權選項從 $799 開始。 此定價架構可滿足不同專案規模與類型的需求,確保您能選擇最適合您的開發與發行計畫的授權。

常見問題解答

C# 中 const 關鍵字的作用是什麼?

在 C# 中,const 關鍵字用於定義常量欄位或在編譯時已知的值,使它們在整個程式中不可變。

如何在 C# 中宣告常數變數?

常量變數是使用 const 關鍵字來宣告,後面跟著資料類型和初始值。例如,const int myConstValue = 100;

C# 中 const 與 readonly 有何差異?

const 是編譯時常數,必須在宣告時初始化。它是靜態的,無法修改。readonly 變數可以在宣告時或在構建器中指定,允許執行時初始化。

在 C# 中,是否可以在方法中宣告 const 變數?

是的,const 變數可以在一個方法中宣告,稱為局部常數,並且只能在該方法中存取。

IronPdf 如何將 HTML 轉換為 PDF?

IronPDF 使用 ChromePdfRenderer 類將 HTML 轉換為 PDF,它可以將 HTML 字串、檔案或 URL 呈現為 PDF 文件。

如何使用 C# 常數庫?

IronPDF 可使用 C# 常數,如常數 HTML 模板字串,透過將 HTML 內容有效轉換為 PDF 來產生 PDF 文件。

為什麼要在 .NET 應用程式中使用 IronPDF?

IronPDF for .NET 用於在 .NET 應用程式中建立、編輯和讀取 PDF 文件,透過將 HTML 轉換為 PDF 來簡化 PDF 的產生,同時保留版面和樣式。

什麼是 C# 中的編譯時常數?

編譯時常數是在編譯時評估和固定的值。const 關鍵字可以確保變數為編譯時常數。

什麼是 C# 中的靜態構建器?

靜態建構器會初始化類別的靜態欄位,並在建立任何實體或存取靜態成員之前自動呼叫。

什麼是 C# 中的常數表達式?

常量表達式是一種可以在編譯時完全評估的表達式,允許在 const 聲明中使用。

Jacob Mellor, Team Iron 首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技術官,作為 C# PDF 技術的先鋒工程師。作為 Iron Software 核心代碼的原作者,他自開始以來塑造了公司產品架構,與 CEO Cameron Rimington 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。

Jacob 持有曼徹斯特大學土木工程一級榮譽学士工程學位(BEng) (1998-2001)。他於 1999 年在倫敦開設了他的第一家軟件公司,並於 2005 年製作了他的首個 .NET 組件,專注於解決 Microsoft 生態系統內的複雜問題。

他的旗艦產品 IronPDF & Iron Suite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。