.NET 幫助

C#選用參數(對開發人員的運作方式)

發佈 2024年4月29日
分享:

在 C# 中,可选参数或可选引数提供了一种通过允许省略某些参数来简化函数调用的方法。此功能通过减少所需的重载方法数量来增强代码的可读性和可维护性。当方法定义中的参数声明了默认值时,它变为可选的,这意味着在调用方法时可以省略它。我们将探索 選擇性參數IronPDF 庫.

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

在上面的代碼片段中,'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
VB   C#

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

使用具名和可选参数

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

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

static void Main()
{
    ConfigureDevice("Router", timeout: 60);
}
static void Main()
{
    ConfigureDevice("Router", timeout: 60);
}
Shared Sub Main()
	ConfigureDevice("Router", timeout:= 60)
End Sub
VB   C#

此呼叫使用一個可選參數來指定 timeout 的值,並使用 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
VB   C#

調用方法

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

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

預設值必須為常量表達式

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

正確使用預設值

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

重載與可選參數

當方法重載涉及為不同的使用案例創建多個方法簽名時,使用可選參數則允許單個方法處理多種情境。

通過代碼比較

重載方法可能如下所示:

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

使用選擇性參數的等效方法:

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

C# 選擇性參數(對開發人員的運作方式):圖 1 - 選擇性參數輸出

使用可选参数的好处

可选参数简化了方法接口,减少了对大量重载的需求。它们使方法更加灵活,并使代码库更易于维护和理解。

可選參數的挑戰

如果過度使用,可選參數可能會導致對每個方法期望和要求的混淆。它們可能會掩蓋方法的意圖,特別是在參數眾多或預設值不明顯的情況下。

最佳實踐

  1. 限制可選參數:謹慎使用可選參數,以避免過於複雜的方法簽名。

  2. 使用具名參數:在方法調用中使用具名參數以提高清晰度,特別是在跳過某些可選參數時。

  3. 記錄默認值:記錄每個參數的作用及其默認值的含義,以防止誤用或混淆。

利用 IronPDF 及 C# 可選參數

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

將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";
        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";
        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"
		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
VB   C#

這裡是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開發人員的強大工具,提供了 免費試用 供那些希望測試其功能的人使用。持續使用的許可證費用從 $749 起,提供專業級 PDF 操作的經濟實惠解決方案。

< 上一頁
C# 子字串(開發者如何運作)
下一個 >
Resharper C#(它如何為開發人員工作)

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

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