跳過到頁腳內容
.NET幫助

C# Optional Parameters(對於開發者的運行原理)

在 C# 中定義可選參數

基本語法

要定義可選參數,您需要在方法的聲明中為其分配一個默認值。 這個默認值必須是一個常量表達式。 如下是如何在方法定義中定義一個或多個可選默認參數的方法:

public static void DisplayGreeting(string message, string end = "!")
{
    Console.WriteLine(message + end);
}
public static void DisplayGreeting(string message, string end = "!")
{
    Console.WriteLine(message + end);
}
Public Shared Sub DisplayGreeting(ByVal message As String, Optional ByVal [end] As String = "!")
	Console.WriteLine(message & [end])
End Sub
$vbLabelText   $csharpLabel

在上述代碼片段中,'end' 是一個默認參數值為 '!' 的可選參數。 這允許方法在調用時可以選擇是否提供第二個參數。

使用可選參數的方法調用

以下是調用上述方法的兩種方式:

static void Main()
{
    DisplayGreeting("Hello"); // Outputs: Hello!
    DisplayGreeting("Hello", "?"); // Outputs: Hello?
}
static void Main()
{
    DisplayGreeting("Hello"); // Outputs: Hello!
    DisplayGreeting("Hello", "?"); // Outputs: Hello?
}
Shared Sub Main()
	DisplayGreeting("Hello") ' Outputs: Hello!
	DisplayGreeting("Hello", "?") ' Outputs: Hello?
End Sub
$vbLabelText   $csharpLabel

第一次調用省略了第二個參數,使用默認值。 第二次調用提供了一個具體值,覆蓋了默認值。

利用命名參數和可選參數

C# 中的命名參數和可選參數提高了涉及可選參數的方法調用的清晰度。 它們允許在調用中直接命名參數來指定哪些參數正在賦值。

使用命名參數的示例

// Named parameters
public static void ConfigureDevice(string deviceName, bool enableLogging = false, int timeout = 30)
{
    Console.WriteLine($"Configuring {deviceName}: Logging={(enableLogging ? "On" : "Off")}, Timeout={timeout}s");
}
// Named parameters
public static void ConfigureDevice(string deviceName, bool enableLogging = false, int timeout = 30)
{
    Console.WriteLine($"Configuring {deviceName}: Logging={(enableLogging ? "On" : "Off")}, Timeout={timeout}s");
}
' Named parameters
Public Shared Sub ConfigureDevice(ByVal deviceName As String, Optional ByVal enableLogging As Boolean = False, Optional ByVal timeout As Integer = 30)
	Console.WriteLine($"Configuring {deviceName}: Logging={(If(enableLogging, "On", "Off"))}, Timeout={timeout}s")
End Sub
$vbLabelText   $csharpLabel

您可以使用命名參數來指定順序錯亂的值或跳過可選參數。

static void Main()
{
    ConfigureDevice("Router", timeout: 60);
}
static void Main()
{
    ConfigureDevice("Router", timeout: 60);
}
Shared Sub Main()
	ConfigureDevice("Router", timeout:= 60)
End Sub
$vbLabelText   $csharpLabel

這次調用使用可選參數指定了超時的值,而使用默認值為 enableLogging。

結合固定參數和可選參數

方法可以同時擁有所需參數(固定參數)和可選參數。 所需參數必須始終在方法聲明中位於可選參數之前,如以下代碼片段所示。

代碼示例

public static void CreateProfile(string firstName, string lastName, int age = 25, string city = "Unknown")
{
    Console.WriteLine($"Name: {firstName} {lastName}, Age: {age}, City: {city}");
}
public static void CreateProfile(string firstName, string lastName, int age = 25, string city = "Unknown")
{
    Console.WriteLine($"Name: {firstName} {lastName}, Age: {age}, City: {city}");
}
Public Shared Sub CreateProfile(ByVal firstName As String, ByVal lastName As String, Optional ByVal age As Integer = 25, Optional ByVal city As String = "Unknown")
	Console.WriteLine($"Name: {firstName} {lastName}, Age: {age}, City: {city}")
End Sub
$vbLabelText   $csharpLabel

調用方法

static void Main()
{
    CreateProfile("John", "Doe"); // Uses default age and city
    CreateProfile("Jane", "Doe", 30, "New York"); // Specifies all parameters
}
static void Main()
{
    CreateProfile("John", "Doe"); // Uses default age and city
    CreateProfile("Jane", "Doe", 30, "New York"); // Specifies all parameters
}
Shared Sub Main()
	CreateProfile("John", "Doe") ' Uses default age and city
	CreateProfile("Jane", "Doe", 30, "New York") ' Specifies all parameters
End Sub
$vbLabelText   $csharpLabel

這種省略參數的靈活性允許在不同上下文中使用同一個方法而不需要多重重載。

默認值必須是常量表達式

可選參數的默認值必須是常量表達式,這些表達式在編譯時進行評估。這可確保默認值始終是穩定和可預測的。

默認值的正確使用

public static void SendEmail(string address, string subject = "No Subject", string body = "")
{
    Console.WriteLine($"Sending email to {address}\nSubject: {subject}\nBody: {body}");
}
public static void SendEmail(string address, string subject = "No Subject", string body = "")
{
    Console.WriteLine($"Sending email to {address}\nSubject: {subject}\nBody: {body}");
}
Imports Microsoft.VisualBasic

Public Shared Sub SendEmail(ByVal address As String, Optional ByVal subject As String = "No Subject", Optional ByVal body As String = "")
	Console.WriteLine($"Sending email to {address}" & vbLf & "Subject: {subject}" & vbLf & "Body: {body}")
End Sub
$vbLabelText   $csharpLabel

重載與可選參數

雖然方法重載涉及為不同用例創建多個方法簽名,而使用可選參數允許單個方法處理各種場景。

通過代碼進行比較

重載的方法可能如下所示:

// Method overloading
public static void Alert(string message)
{
    Console.WriteLine(message);
}

public static void Alert(string message, bool urgent)
{
    if (urgent)
        Console.WriteLine("Urgent: " + message);
    else
        Console.WriteLine(message);
}
// Method overloading
public static void Alert(string message)
{
    Console.WriteLine(message);
}

public static void Alert(string message, bool urgent)
{
    if (urgent)
        Console.WriteLine("Urgent: " + message);
    else
        Console.WriteLine(message);
}
' Method overloading
Public Shared Sub Alert(ByVal message As String)
	Console.WriteLine(message)
End Sub

Public Shared Sub Alert(ByVal message As String, ByVal urgent As Boolean)
	If urgent Then
		Console.WriteLine("Urgent: " & message)
	Else
		Console.WriteLine(message)
	End If
End Sub
$vbLabelText   $csharpLabel

使用可選參數的等效方法:

public static void Alert(string message, bool urgent = false)
{
    if (urgent)
        Console.WriteLine("Urgent: " + message);
    else
        Console.WriteLine(message);
}
public static void Alert(string message, bool urgent = false)
{
    if (urgent)
        Console.WriteLine("Urgent: " + message);
    else
        Console.WriteLine(message);
}
Public Shared Sub Alert(ByVal message As String, Optional ByVal urgent As Boolean = False)
	If urgent Then
		Console.WriteLine("Urgent: " & message)
	Else
		Console.WriteLine(message)
	End If
End Sub
$vbLabelText   $csharpLabel

C# 可選參數(開發人員如何使用):圖 1 - 可選參數輸出

使用可選參數的好處

可選參數簡化方法接口並減少多重重載的需求。 它們使方法更靈活並使代碼庫更易於維護和理解。

可選參數的挑戰

如果過度使用,可選參數可能會導致對每個方法期望和執行所需內容的混淆。 它們可能會掩蓋方法的意圖,尤其是當有很多參數或者默認值不言自明時。

最佳實踐

  1. 限制可選參數:明智地使用可選參數以避免過於複雜的方法簽名。
  2. 使用命名參數:提高方法調用的清晰度,特別是當跳過某些可選參數時。
  3. 記錄默認值:記錄每個參數的功能和默認值所暗含的意義,以防誤用或混淆。

使用 C# 可選參數与 IronPDF 結合

C# 可選參數(開發人員如何使用):圖 2 - IronPDF

IronPDF 是一個實用的 .NET 庫,允許開發人員直接在其應用中創建、操作和渲染 PDF 文件。 它高效地將 HTML 轉換為 PDF進行 PDF 轉換。 這個 HTML 可以是各種形式,如 HTML 字符串,HTML 文件或 URL。 它非常適合需要動態生成 PDF 文件的應用程序,比如發票,報告或定製用戶檔案。 使用 IronPDF,開發人員可以充分利用 .NET Framework 高效地處理 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 與 C# 可選參數結合,可以使生成 PDF 文件的過程變得簡單。 通過使用可選參數,開發人員可以創建靈活的 PDF 生成方法,能夠適應不同的輸入和需求,且只需極少量的方法重載。

代碼示例

下面是如何使用 IronPDF 結合 C# 可選參數生成自定制 PDF 報告的示例,這可能調整細節如報告標題,以及是否包括某些報告章節:

using IronPdf;
using System;

public class PdfReportGenerator
{
    // Method to generate PDF with optional parameters
    public static void CreatePdfReport(string htmlContent, string filePath = "Report.pdf", bool includeCharts = true, string reportTitle = "Monthly Report")
    {
        // Optional parameters allow customization of the report's title and content dynamically
        var renderer = new ChromePdfRenderer();
        // Customize the PDF document
        renderer.RenderingOptions.TextHeader.CenterText = reportTitle;
        renderer.RenderingOptions.TextFooter.CenterText = "Generated on " + DateTime.Now.ToString("dd-MM-yyyy");
        renderer.RenderingOptions.MarginTop = 50;  // Set the top margin
        renderer.RenderingOptions.MarginBottom = 50;  // Set the bottom margin
        if (!includeCharts)
        {
            // Modify HTML content to remove chart sections if not included
            htmlContent = htmlContent.Replace("<div class='charts'></div>", "");
        }
        // Render the HTML to PDF
        PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);
        // Save the generated PDF to a file
        pdf.SaveAs(filePath);
        Console.WriteLine($"PDF report has been created at {filePath}");
    }

    static void Main()
    {
        License.LicenseKey = "License-Key"; // Specify the license key if required
        string htmlTemplate = @"
        <html>
        <head>
            <title>Monthly Report</title>
        </head>
        <body>
            <h1>Monthly Performance Report</h1>
            <p>This section contains text describing the overall performance for the month.</p>
            <div class='charts'>
                <h2>Sales Charts</h2>
                <!-- Placeholder for charts -->
            </div>
        </body>
        </html>";

        // Call the CreatePdfReport method with different parameters
        CreatePdfReport(htmlTemplate, "BasicReport.pdf", false, "Basic Monthly Report");
        CreatePdfReport(htmlTemplate, "FullReport.pdf", true, "Detailed Monthly Report");
    }
}
using IronPdf;
using System;

public class PdfReportGenerator
{
    // Method to generate PDF with optional parameters
    public static void CreatePdfReport(string htmlContent, string filePath = "Report.pdf", bool includeCharts = true, string reportTitle = "Monthly Report")
    {
        // Optional parameters allow customization of the report's title and content dynamically
        var renderer = new ChromePdfRenderer();
        // Customize the PDF document
        renderer.RenderingOptions.TextHeader.CenterText = reportTitle;
        renderer.RenderingOptions.TextFooter.CenterText = "Generated on " + DateTime.Now.ToString("dd-MM-yyyy");
        renderer.RenderingOptions.MarginTop = 50;  // Set the top margin
        renderer.RenderingOptions.MarginBottom = 50;  // Set the bottom margin
        if (!includeCharts)
        {
            // Modify HTML content to remove chart sections if not included
            htmlContent = htmlContent.Replace("<div class='charts'></div>", "");
        }
        // Render the HTML to PDF
        PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);
        // Save the generated PDF to a file
        pdf.SaveAs(filePath);
        Console.WriteLine($"PDF report has been created at {filePath}");
    }

    static void Main()
    {
        License.LicenseKey = "License-Key"; // Specify the license key if required
        string htmlTemplate = @"
        <html>
        <head>
            <title>Monthly Report</title>
        </head>
        <body>
            <h1>Monthly Performance Report</h1>
            <p>This section contains text describing the overall performance for the month.</p>
            <div class='charts'>
                <h2>Sales Charts</h2>
                <!-- Placeholder for charts -->
            </div>
        </body>
        </html>";

        // Call the CreatePdfReport method with different parameters
        CreatePdfReport(htmlTemplate, "BasicReport.pdf", false, "Basic Monthly Report");
        CreatePdfReport(htmlTemplate, "FullReport.pdf", true, "Detailed Monthly Report");
    }
}
Imports IronPdf
Imports System

Public Class PdfReportGenerator
	' Method to generate PDF with optional parameters
	Public Shared Sub CreatePdfReport(ByVal htmlContent As String, Optional ByVal filePath As String = "Report.pdf", Optional ByVal includeCharts As Boolean = True, Optional ByVal reportTitle As String = "Monthly Report")
		' Optional parameters allow customization of the report's title and content dynamically
		Dim renderer = New ChromePdfRenderer()
		' Customize the PDF document
		renderer.RenderingOptions.TextHeader.CenterText = reportTitle
		renderer.RenderingOptions.TextFooter.CenterText = "Generated on " & DateTime.Now.ToString("dd-MM-yyyy")
		renderer.RenderingOptions.MarginTop = 50 ' Set the top margin
		renderer.RenderingOptions.MarginBottom = 50 ' Set the bottom margin
		If Not includeCharts Then
			' Modify HTML content to remove chart sections if not included
			htmlContent = htmlContent.Replace("<div class='charts'></div>", "")
		End If
		' Render the HTML to PDF
		Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(htmlContent)
		' Save the generated PDF to a file
		pdf.SaveAs(filePath)
		Console.WriteLine($"PDF report has been created at {filePath}")
	End Sub

	Shared Sub Main()
		License.LicenseKey = "License-Key" ' Specify the license key if required
		Dim htmlTemplate As String = "
        <html>
        <head>
            <title>Monthly Report</title>
        </head>
        <body>
            <h1>Monthly Performance Report</h1>
            <p>This section contains text describing the overall performance for the month.</p>
            <div class='charts'>
                <h2>Sales Charts</h2>
                <!-- Placeholder for charts -->
            </div>
        </body>
        </html>"

		' Call the CreatePdfReport method with different parameters
		CreatePdfReport(htmlTemplate, "BasicReport.pdf", False, "Basic Monthly Report")
		CreatePdfReport(htmlTemplate, "FullReport.pdf", True, "Detailed Monthly Report")
	End Sub
End Class
$vbLabelText   $csharpLabel

以下是 FullReport PDF 文件預覽:

C# 可選參數(開發人員如何使用):圖 3 - PDF 報告輸出

代碼示例中的 CreatePdfReport 方法的結構是從 HTML 文件內容生成 PDF 文件,提供了靈活的可選參數如文件路徑、是否包含圖表和報告標題。 這種設計使方法能夠藉由很少的代碼調整來適應不同報告需求。 在此方法內,IronPDF 的設置已調整為在 PDF 中包含自定義的頁眉和頁腳,這些設置顯示出報告標題和報告生成日期。

邊距也被配置為改善文檔的視覺佈局。 根據 includeCharts 參數為 true 或 false,動態修改 HTML 文件內容以包含或不包含圖表視覺效果。 最終,可能已經修改的 HTML 被轉換成 PDF 並保存到指定位置。 此示例展示了可選參數如何顯著簡化製作定制化 PDF 報告的過程。

結論

C# 可選參數(開發人員如何使用):圖 4 - 授權

總之,可選參數通過減少多重重載方法的需求,允許開發者創建更靈活和可維護的代碼。 透過將 C# 可選參數與 IronPDF 庫結合,開發人員可以高效地生成自定制的 PDF 文件。 這種整合不僅簡化了代碼庫,還增強了功能,使其更容易適應不同的報告要求或用戶偏好。

IronPDF 本身對任何希望將 PDF 功能集成到應用中的 .NET 開發者來說是一個強大的工具,對於希望測試其功能的開發者提供免費的 IronPDF 試用版。 對於持續使用,授權價格從$799起,是專業級 PDF 操作的一個經濟高效的解決方案。

常見問題解答

什麼是 C# 中的選擇性參數以及如何使用?

C# 中的選擇性參數允許開發人員通過為某些參數指定預設值來定義可以以較少參數調用的方法。這意味著如果在方法調用中省略了參數,將使用預設值。

命名參數如何提升 C# 代碼的可讀性?

命名參數通過允許開發人員在方法調用中直接指定參數值,從而提升代碼的可讀性。這在處理具有多個參數的方法時特別有用,因為它能夠解釋哪些參數對應於哪些參數值。

C# 中選擇性參數和方法重載有什麼區別?

選擇性參數允許單個方法處理不同數量的參數,而方法重載則涉及創建具有不同參數的多個方法版本。選擇性參數通過避免多個方法定義來減少複雜性。

在使用 .NET 庫進行 PDF 生成時,選擇性參數如何提供幫助?

在使用 .NET 庫生成 PDF 時,選擇性參數可以通過允許開發人員僅指定生成 PDF 所需的參數來簡化方法調用。這種靈活性有助於自定義 PDF 內容、佈局和文件屬性,而不需要多個重載。

在 C# 中使用選擇性參數的最佳實踐是什麼?

使用選擇性參數的最佳實踐包括限制使用以避免混淆,確保預設值有良好的文檔記錄,並將其與命名參數結合使用以提高方法調用的清晰度。

結合固定和選擇性參數對方法設計有何益處?

結合固定和選擇性參數允許開發人員強制某些輸入同時提供其他輸入的靈活性。這種設計策略確保提供必要的數據,同時簡化了方法界面中的其他非必需輸入。

如何使用 C# 中的選擇性參數簡化 PDF 報告生成?

C# 中的選擇性參數可以通過允許開發人員僅指定必要數據(如標題或作者),同時使用其他參數(如文件路徑或頁面佈局)的預設設置來簡化 PDF 報告生成,從而減少多個方法版本的需求。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。