C# Optional Parameters(對於開發者的運行原理)
Defining Optional Parameters in C#
基本語法
要定義一個可選參數,您需要在方法的宣告中為其指定一個預設值。 此預設值必須是一個常數表達式。 以下是如何在方法定義中定義具有一個或多個可選預設參數的方法:
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 SubPublic 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 SubShared 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' 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 SubShared 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 SubPublic 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 SubShared 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 SubImports 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
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' 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 SubPublic 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
使用可選參數的好處
可選參數簡化了方法介面並減少了大量重載的需求。 它們讓方法更加靈活,並使程式碼庫更易於維護和理解。
可選參數的挑戰
如果過度使用,可選參數可能會導致對每個方法所需內容的混淆。 它們可能會模糊方法的意圖,特別是當參數較多或預設值不易理解時。
最佳實踐
- 限制可選參數:謹慎使用可選參數,以避免過於複雜的方法簽名。
- 使用命名引數:增強方法調用的清晰度,尤其是在略過某些可選參數時。
- 記錄預設值:記錄每個參數的作用及預設值的含義,以防止誤用或混淆。
在IronPDF中使用C# 可選參數

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
Module Program
Sub Main(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 ModuleImports IronPdf
Module Program
Sub Main(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 Module將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>
<!-- 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 ClassImports 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這是FullReport PDF文件預覽:

程式碼範例中的CreatePdfReport方法被設計為從HTML內容生成PDF文件,並且在檔案路徑、圖表包含和報告標題等可選參數上提供靈活性。 這樣的設計允許方法隨著少量程式碼調整適應不同報告需求。 在方法中,IronPDF 設定被調整為在PDF中包含自定義頁眉和頁腳,這些頁眉和頁腳設置為顯示報告標題和報告生成日期。
頁邊距也配置以改善文件的視覺佈局。 根據includeCharts參數是否為真,HTML內容會動態修改以包含或排除圖表視覺效果。 最後,潛在地修改過的HTML被轉換為PDF並保存到指定位置。 此範例展示了可選參數如何顯著簡化建立定制PDF報告的過程。
結論
總之,可選參數允許開發人員通過減少多重重載方法的需求來建立更靈活和可維護的程式碼。 通過將C#可選參數與IronPDF程式庫結合,開發人員可以高效地生成自訂PDF文件。 這種整合不僅簡化了程式碼庫,還增強了功能,使其更易於適應不同的報告要求或使用者偏好。
IronPDF本身是一個強大的工具,適合任何希望將PDF功能整合到應用中的.NET開發人員,並為希望測試其能力的人 提供免費的IronPDF試用。 持續使用的授權從$999起,為專業級PDF操作提供經濟有效的解決方案。
Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。