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
在上述程式碼片段中,"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
第一次呼叫省略了第二個參數,使用預設值。 第二次呼叫提供特定值,覆寫預設值。
使用命名和可選參數
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
您可以使用命名參數來指定不按順序的值或跳過可選參數。
static void Main()
{
ConfigureDevice("Router", timeout: 60);
}
static void Main()
{
ConfigureDevice("Router", timeout: 60);
}
Shared Sub Main()
ConfigureDevice("Router", timeout:= 60)
End Sub
此呼叫使用可選參數指定逾時值,同時使用 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
呼叫方法
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
這種省略參數的彈性可讓相同的方法在不同的上下文中使用,而不需要多個重載。
預設值必須是常數表達式
可選參數的預設參數必須是常數表達式,在編譯時進行評估。這可確保預設值始終穩定且可預測。
正確使用預設值
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
超載與可選參數
方法重載(method overloading)涉及為不同的使用情況建立多個方法簽章,而使用可選參數則可讓單一方法處理各種情況。
透過程式碼進行比較
重載方法可能是這樣的
// 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
使用可選參數的等效方法:
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

使用可選參數的好處
可選參數可簡化方法介面,並減少大量重載的需求。 它們讓方法更靈活,讓程式碼更容易維護和理解。
可選參數的挑戰
如果過度使用可選參數,可能會造成混淆,不清楚每種方法為了正確執行所期望和需要的參數。 這些詞彙可能會模糊方法的本意,尤其是當參數眾多或預設值無法自明時。
最佳實務
1.限制可選參數:謹慎使用可選參數,避免方法簽章過於複雜。 2.使用命名參數:提高方法呼叫的清晰度,特別是省略某些可選參數時。 3.記錄預設值:記錄每個參數的作用以及預設值的意義,以防止誤用或混淆。
使用 IronPDF 與 C# 可選參數。

IronPDF for .NET 是一個有用的 .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
結合 IronPDF 與 C# 可選參數,可以讓 PDF 文件的生成過程變得簡單。 透過使用可選參數,開發人員可以建立彈性的 PDF 產生方法,以最小的方法重載來適應不同的輸入和需求。
程式碼範例
以下是一個範例,展示如何使用 IronPDF 搭配 C# 可選參數,從簡單的 HTML 模版產生客製化的 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>
</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>
</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(htmlContent As String, Optional filePath As String = "Report.pdf", Optional includeCharts As Boolean = True, Optional reportTitle As String = "Monthly Report")
' Optional parameters allow customization of the report's title and content dynamically
Dim renderer As 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>
</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
以下是 FullReport PDF 檔案預覽:

程式碼範例中的 CreatePdfReport 方法的結構是從 HTML 內容產生 PDF 文件,提供彈性的可選參數,例如檔案路徑、包含圖表和報告標題。 此設計允許該方法只需稍微調整程式碼即可適應不同的報告需求。 在該方法中,調整 IronPDF 設定,在 PDF 中加入自訂的頁首和頁尾,設定為顯示報告標題和報告產生日期。
此外,還配置了邊界以改善文件的視覺排版。 根據 includeCharts 參數的真假,HTML 內容會被動態修改為包含或排除圖表視覺效果。 最後,將可能修改的 HTML 轉換成 PDF 並儲存到指定位置。 本範例展示可選參數如何大幅簡化建立量身訂做 PDF 報告的流程。
結論

總而言之,可選參數可讓開發人員透過減少對多重重載方法的需求,來建立更具彈性與可維護性的程式碼。 透過結合 C# 可選參數與 IronPDF 函式庫,開發人員可以有效率地產生客製化 PDF 文件。 這種整合不僅能簡化程式碼庫,還能增強功能,使其更容易適應不同的報告需求或使用者偏好。
IronPDF 本身是一款功能強大的工具,適合任何希望將 PDF 功能整合至其應用程式的 .NET 開發人員使用,並提供 開發人員免費 IronPDF 試用版,供希望測試其功能的人員使用。 對於持續使用,許可證從 $999 開始,為專業級 PDF 處理提供經濟高效的解決方案。
常見問題解答
什麼是 C# 中的選擇性參數以及如何使用?
C# 中的選擇性參數允許開發人員通過為某些參數指定預設值來定義可以以較少參數調用的方法。這意味著如果在方法調用中省略了參數,將使用預設值。
命名參數如何提升 C# 代碼的可讀性?
命名參數通過允許開發人員在方法調用中直接指定參數值,從而提升代碼的可讀性。這在處理具有多個參數的方法時特別有用,因為它能夠解釋哪些參數對應於哪些參數值。
C# 中選擇性參數和方法重載有什麼區別?
選擇性參數允許單個方法處理不同數量的參數,而方法重載則涉及創建具有不同參數的多個方法版本。選擇性參數通過避免多個方法定義來減少複雜性。
在使用 .NET 庫進行 PDF 生成時,選擇性參數如何提供幫助?
在使用 .NET 庫生成 PDF 時,選擇性參數可以通過允許開發人員僅指定生成 PDF 所需的參數來簡化方法調用。這種靈活性有助於自定義 PDF 內容、佈局和文件屬性,而不需要多個重載。
在 C# 中使用選擇性參數的最佳實踐是什麼?
使用選擇性參數的最佳實踐包括限制使用以避免混淆,確保預設值有良好的文檔記錄,並將其與命名參數結合使用以提高方法調用的清晰度。
結合固定和選擇性參數對方法設計有何益處?
結合固定和選擇性參數允許開發人員強制某些輸入同時提供其他輸入的靈活性。這種設計策略確保提供必要的數據,同時簡化了方法界面中的其他非必需輸入。
如何使用 C# 中的選擇性參數簡化 PDF 報告生成?
C# 中的選擇性參數可以通過允許開發人員僅指定必要數據(如標題或作者),同時使用其他參數(如文件路徑或頁面佈局)的預設設置來簡化 PDF 報告生成,從而減少多個方法版本的需求。



