.NET幫助 C# 常量(對於開發者的運行原理) Curtis Chau 更新日期:7月 28, 2025 Download IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article 在 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 此示例說明了在類中使用常量整數(const int)的簡單方法。 MaxSize 常量在同一類中是可訪問的,可以在 static void Main 方法中直接使用。 const vs. readonly 變量 儘管 const 和 readonly 關鍵字都用於聲明不可變值,但它們之間存在重要差異。 const 字段是一個編譯時常量,這意味著它的值是在編譯時確定的,並直接嵌入到中間語言(IL)代碼中。 這使其成為靜態的,且不能被修改。 另一方面,readonly 變量可以在聲明時或在類的構造函數中分配。 這允許一定的靈活性,因為 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 const 變量的作用域 常量變量可以在方法內聲明或作為類的成員聲明。 當您在方法中聲明 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 相比之下,當 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# 中的 const 和 readonly 基礎,理解如何處理常量表達式、靜態構造函數和靜態字段可以提升您的編碼實踐,特別是當處理需要在類的實例間共享的常量值時。 常量表達式 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 靜態方法訪問,展示了靜態構造函數如何用於初始化值在運行時未知道的 readonly 字段。 靜態字段以及 readonly 和 static 關鍵字 靜態字段屬於類,而不是類的任何實例,並使用 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 简介 IronPDF 是一個多功能的庫,允許開發者在 .NET 應用程序中創建、編輯和閱讀 PDF 文件。 這個強大的工具通過允許開發者將 HTML 轉換為 PDF、操作內容並輕鬆從 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 集成到 .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 並保存到指定的文件路徑。 這展示了如何利用 const 關鍵字定義不可變的 HTML 模板,來輕鬆使用 IronPDF 生成靜態 HTML 內容的 PDF。 輸出 以下是輸出 PDF 文件: 結論 在 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 字符串、文件或 URL 呈現為 PDF 文件來將 HTML 轉換為 PDF。 如何將庫與 C# 常量一起使用? IronPDF 可以使用 C# 常量,例如一個常量的 HTML 模板字符串,來通過將 HTML 內容高效地轉換為 PDF 來生成 PDF 文件。 為什麼在 .NET 應用程序中使用 IronPDF? IronPDF 用於在 .NET 應用程序中創建、編輯和閱讀 PDF 文檔,通過將 HTML 轉換為 PDF 簡化 PDF 生成,同時保留其佈局和風格。 C# 中的編譯時常量是什麼? 編譯時常量是在編譯時評估和固定的值。const 關鍵字確保變數是一個編譯時常量。 C# 中的靜態構造函數是什麼? 靜態構造函數初始化一個類的靜態欄位,並在創建任何實例或訪問靜態成員之前自動調用。 C# 中的常量表達式是什麼? 常量表達式是一個可以在編譯時完全評估的表達式,允許它在 const 聲明中使用。 Curtis Chau 立即與工程團隊聊天 技術作家 Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。 相關文章 更新日期 9月 4, 2025 RandomNumberGenerator C# 使用RandomNumberGenerator C#類可以幫助將您的PDF生成和編輯項目提升至新水準 閱讀更多 更新日期 9月 4, 2025 C#字符串等於(它如何對開發者起作用) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 更新日期 8月 5, 2025 C#開關模式匹配(對開發者來說是如何工作的) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 C# 線程休眠方法(對於開發者的運行原理)RabbitMQ C#(對於開發者的運...