.NET 幫助

C# 常數(它如何為開發者運作)

發佈 2024年3月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# 常數(它對開發者的作用):圖 1 - 常數輸出

這個例子說明了常量整數的簡單使用 (const int) 在類別內。MaxSize 常數在同一個類別內是可以訪問的,並且可以直接在 static void Main 方法中使用。

const vs. readonly 變數

constreadonly 關鍵字都用來宣告不可變的值,但它們之間有重要的區别。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
VB   C#

C# 常數(開發人員如何使用):圖2 - 只讀欄位輸出

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
VB   C#

C# 常數(開發者如何使用):圖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
VB   C#

常數和靜態成員在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
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靜態方法訪問,展示了靜態構造函數如何用直到運行時才知道的值來初始化只讀字段。

靜態欄位和 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
VB   C#

此範例演示了使用靜態建構函式初始化一個 readonly 靜態字段 MaxUsers,其值是在運行時檢索的,可能來自配置文件。const 字段 TimeoutSeconds 代表一個編譯時常數,直接嵌入到代碼中。

IronPDF 介紹

C# 常數(如何為開發人員工作):圖 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 及 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
VB   C#

在此範例中,HtmlTemplate 常量被定義為簡單的 HTML 內容,作為我們 PDF 文件的來源。CreatePdf 方法利用 IronPDF 的 ChromePdfRenderer 類來將這些 HTML 轉換為 PDF 並保存到指定的文件路徑。這展示了 IronPDF 能夠輕鬆地從靜態 HTML 內容生成 PDF,並使用 const 關鍵字來定義不可變的 HTML 模板。

輸出

這是輸出 PDF 文件:

C# 常量(它如何為開發人員工作):圖 5 - PDF 輸出

結論

C# 常數(開發人員如何使用):圖 6 - 許可

在C#中,const關鍵字是一個有價值的功能,用於定義在編譯時已知的不可變值。它通過明確指出哪些值是常量,來幫助提升代碼的可讀性和可維護性。請記住,const 變量是隱式靜態的,必須在聲明時初始化,且其值必須是編譯時常量。相比之下,readonly 變量提供了更多的靈活性,但在運行時初始化。

IronPDF不僅以其強大的PDF操作功能而著稱,還因其靈活的採用模式脫穎而出。針對想要探索其功能的開發者和組織,IronPDF提供 免費試用,提供了一個很好的機會來評估其功能和整合的便利性,無需初期投資。

當您準備好使用IronPDF進行商業用途時,授權選項從Lite License開始。這樣的定價結構旨在滿足不同項目規模和類型的需求,確保您可以選擇最適合您的開發和分發計劃的授權。

< 上一頁
C# Thread Sleep 方法(對開發人員的運作方式)
下一個 >
RabbitMQ C#(開發人員如何使用)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >