C# Params(對於開發者的運行原理)
C# 中的 params 關鍵字是在 .NET 中一個強大的功能,允許方法接受可變數量的參數。 這可以顯著簡化呼叫需要變動參數數量的方法時的語法。 在這篇全面指南中,我們將探索 C# 中的 params 關鍵字、其語法、使用案例和最佳實踐。 本文稍後我們將介紹來自 Iron Software 的 IronPDF 程式庫,並解釋如何使用 params 關鍵字與 IronPDF 生成 PDF。
C# 的 Params 參數型別是什麼?
在 C# 的領域,方法通常遵循一組預定義的參數。 然而,有些情況可能會讓人不確定方法預定的參數數量。 引入 "params" 關鍵字,它是一種解決方案,使得方法參數能夠容納一組參數的陣列。 當開發者不確定確切的參數數量時,這項功能非常有價值,有助於在方法定義中傳遞不定數量或可選的同一型別的參數。
public class ParamsExample
{
// Method accepting a variable number of string arguments using the params keyword
public void PrintMessages(params string[] messages)
{
foreach (var message in messages)
{
Console.WriteLine(message);
}
}
}
// Usage
class Program
{
public static void Main()
{
var example = new ParamsExample();
example.PrintMessages("Hello", "World", "!");
}
// More examples
public static void AddItemsToShoppingBasket(params string[] items)
{
// Implementation to add items to a shopping basket
}
public static void AddItemsSumToShoppingBasket(params int[] sum) // Using params with int
{
// Implementation to add sum of items to the shopping basket
}
}Public Class ParamsExample
' Method accepting a variable number of string arguments using the params keyword
Public Sub PrintMessages(ParamArray ByVal messages() As String)
For Each message In messages
Console.WriteLine(message)
Next message
End Sub
End Class
' Usage
Friend Class Program
Public Shared Sub Main()
Dim example = New ParamsExample()
example.PrintMessages("Hello", "World", "!")
End Sub
' More examples
Public Shared Sub AddItemsToShoppingBasket(ParamArray ByVal items() As String)
' Implementation to add items to a shopping basket
End Sub
Public Shared Sub AddItemsSumToShoppingBasket(ParamArray ByVal sum() As Integer) ' Using params with int
' Implementation to add sum of items to the shopping basket
End Sub
End ClassPublic Class ParamsExample
' Method accepting a variable number of string arguments using the params keyword
Public Sub PrintMessages(ParamArray ByVal messages() As String)
For Each message In messages
Console.WriteLine(message)
Next message
End Sub
End Class
' Usage
Friend Class Program
Public Shared Sub Main()
Dim example = New ParamsExample()
example.PrintMessages("Hello", "World", "!")
End Sub
' More examples
Public Shared Sub AddItemsToShoppingBasket(ParamArray ByVal items() As String)
' Implementation to add items to a shopping basket
End Sub
Public Shared Sub AddItemsSumToShoppingBasket(ParamArray ByVal sum() As Integer) ' Using params with int
' Implementation to add sum of items to the shopping basket
End Sub
End ClassAddItemsToShoppingBasket 方法可以用不同數量的字串參數來調用。 params 關鍵字簡化了方法呼叫的語法,允許開發者直接傳遞可選參數,而無需顯式建立陣列輸入。
class Program
{
public static void Main()
{
AddItemsToShoppingBasket("cake", "pizza", "cold drink");
AddItemsToShoppingBasket("snacks", "burger");
AddItemsToShoppingBasket(); // Valid even with zero parameters, using default value
}
}class Program
{
public static void Main()
{
AddItemsToShoppingBasket("cake", "pizza", "cold drink");
AddItemsToShoppingBasket("snacks", "burger");
AddItemsToShoppingBasket(); // Valid even with zero parameters, using default value
}
}Friend Class Program
Public Shared Sub Main()
AddItemsToShoppingBasket("cake", "pizza", "cold drink")
AddItemsToShoppingBasket("snacks", "burger")
AddItemsToShoppingBasket() ' Valid even with zero parameters, using default value
End Sub
End ClassFriend Class Program
Public Shared Sub Main()
AddItemsToShoppingBasket("cake", "pizza", "cold drink")
AddItemsToShoppingBasket("snacks", "burger")
AddItemsToShoppingBasket() ' Valid even with zero parameters, using default value
End Sub
End Class考量與最佳實踐
-
將 Params 放在參數清單末尾:建議的做法是將參數清單中的 params 參數位於方法的參數列表末尾。這種做法有助於清晰,減少方法調用時的混淆。 需要顯式值的參數應在 params 之前,以便有效組織。
-
明確指定非 params 參數:當使用
params調用方法時,確保明確提供非params參數的值。 這種做法可防止不確定性並保證準確呼叫方法與所需的參數數量一起調用。 -
小心防止模糊:在使用
params的方法中有多重重載或同型別的參數時要特別謹慎。 編譯器可能會難以確定要調用的適當方法,可能會導致模糊錯誤。 -
探索替代方法:雖然
params提供了便利,但在某些情景中考慮替代方法。 使用像List<t>這樣的集合可能對於增強功能更適用,或是當傳遞命名參數符合您的目標時更合適。 -
謹慎將於相關情景運用:在參數數量可變且可能在不同方法呼叫中變動的情景下謹慎運用
params。 保留它的使用於參數數量不可預測的情況中,在參數數量固定且已知時避免運用。
用於參數型別的一維陣列
AddItemsToShoppingBasket 也可以通過調用一個一維陣列來使用。
class Program
{
public static void Main()
{
var items = new string[] { "cold drink", "snack", "roll" }; // 1D string array
AddItemsToShoppingBasket(items); // Works as expected
AddItemsToShoppingBasket("cold drink", "coke", "roll"); // Similar result to the above line
}
}class Program
{
public static void Main()
{
var items = new string[] { "cold drink", "snack", "roll" }; // 1D string array
AddItemsToShoppingBasket(items); // Works as expected
AddItemsToShoppingBasket("cold drink", "coke", "roll"); // Similar result to the above line
}
}Friend Class Program
Public Shared Sub Main()
Dim items = New String() { "cold drink", "snack", "roll" } ' 1D string array
AddItemsToShoppingBasket(items) ' Works as expected
AddItemsToShoppingBasket("cold drink", "coke", "roll") ' Similar result to the above line
End Sub
End ClassFriend Class Program
Public Shared Sub Main()
Dim items = New String() { "cold drink", "snack", "roll" } ' 1D string array
AddItemsToShoppingBasket(items) ' Works as expected
AddItemsToShoppingBasket("cold drink", "coke", "roll") ' Similar result to the above line
End Sub
End Class傳遞一個同型別的逗號分隔參數陣列
AddItemsToShoppingBasket 可以透過在方法呼叫中傳遞變數列表或陣列來調用,如下面所示。
class Program
{
public static void Main()
{
// Example method signature
AddItemsToShoppingBasket("snacks", "burger", "snacks", "burger", "cold drink"); // Comma separated values
AddItemsToShoppingBasket("snacks");
}
}class Program
{
public static void Main()
{
// Example method signature
AddItemsToShoppingBasket("snacks", "burger", "snacks", "burger", "cold drink"); // Comma separated values
AddItemsToShoppingBasket("snacks");
}
}Friend Class Program
Public Shared Sub Main()
' Example method signature
AddItemsToShoppingBasket("snacks", "burger", "snacks", "burger", "cold drink") ' Comma separated values
AddItemsToShoppingBasket("snacks")
End Sub
End ClassFriend Class Program
Public Shared Sub Main()
' Example method signature
AddItemsToShoppingBasket("snacks", "burger", "snacks", "burger", "cold drink") ' Comma separated values
AddItemsToShoppingBasket("snacks")
End Sub
End Class傳遞已定義型別的陣列
陣列應包含 params 方法中所定義相同的型別; 否則,會引發錯誤。
// Example that results in an error
AddItemsToShoppingBasket("snacks", 2, "burger"); // Error due to type mismatch
AddItemsToShoppingBasket(2, 3, 4); // Error since params type is string// Example that results in an error
AddItemsToShoppingBasket("snacks", 2, "burger"); // Error due to type mismatch
AddItemsToShoppingBasket(2, 3, 4); // Error since params type is string' Example that results in an error
AddItemsToShoppingBasket("snacks", 2, "burger") ' Error due to type mismatch
AddItemsToShoppingBasket(2, 3, 4) ' Error since params type is string' Example that results in an error
AddItemsToShoppingBasket("snacks", 2, "burger") ' Error due to type mismatch
AddItemsToShoppingBasket(2, 3, 4) ' Error since params type is string如果方法中所定義的 params 存在型別不匹配會發生語法錯誤。
總是方法中的最後一個參數
在方法簽名中 params 參數之後不允許出現其他參數。 在方法參數宣告中僅允許一個 params 參數。 若定義不正確會導致編譯錯誤。
class Program
{
static void Main(string[] args)
{
// Example 1
public static void AddItemsToShoppingBasket(double total, params string[] items)
{
// Works fine as `params` is the last parameter
}
// Example 2, error scenario
public static void AddItemsToShoppingBasket(params string[] items, decimal total, int total)
{
// Error: `params` keyword must be the last parameter
}
}
}class Program
{
static void Main(string[] args)
{
// Example 1
public static void AddItemsToShoppingBasket(double total, params string[] items)
{
// Works fine as `params` is the last parameter
}
// Example 2, error scenario
public static void AddItemsToShoppingBasket(params string[] items, decimal total, int total)
{
// Error: `params` keyword must be the last parameter
}
}
}Module Program
Sub Main(args As String())
' Example 1
Public Sub AddItemsToShoppingBasket(total As Double, ParamArray items As String())
' Works fine as `ParamArray` is the last parameter
End Sub
' Example 2, error scenario
' Public Sub AddItemsToShoppingBasket(ParamArray items As String(), total As Decimal, total As Integer)
' Error: `ParamArray` keyword must be the last parameter
' End Sub
End Sub
End ModuleModule Program
Sub Main(args As String())
' Example 1
Public Sub AddItemsToShoppingBasket(total As Double, ParamArray items As String())
' Works fine as `ParamArray` is the last parameter
End Sub
' Example 2, error scenario
' Public Sub AddItemsToShoppingBasket(ParamArray items As String(), total As Decimal, total As Integer)
' Error: `ParamArray` keyword must be the last parameter
' End Sub
End Sub
End Module僅一個 params 關鍵字
方法簽名中僅允許一個 params 參數。 如果在方法簽名中找到多於一個 params 關鍵字,編譯器會拋出錯誤。
class Program
{
static void Main(string[] args)
{
public static void AddItemsToShoppingBasket(params string[] items, params string[] quantity)
{
// Compiler Error: Only one params keyword is allowed in the method signature
}
}
}class Program
{
static void Main(string[] args)
{
public static void AddItemsToShoppingBasket(params string[] items, params string[] quantity)
{
// Compiler Error: Only one params keyword is allowed in the method signature
}
}
}Friend Class Program
Shared Sub Main(ByVal args() As String)
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
' public static void AddItemsToShoppingBasket(params string[] items, params string[] quantity)
' {
' ' Compiler Error: Only one params keyword is allowed in the method signature
' }
End Sub
End ClassFriend Class Program
Shared Sub Main(ByVal args() As String)
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
' public static void AddItemsToShoppingBasket(params string[] items, params string[] quantity)
' {
' ' Compiler Error: Only one params keyword is allowed in the method signature
' }
End Sub
End Class您可以不傳遞任何參數
如果方法有一個 params 關鍵字的參數,則可以在無需任何參數的情況下調用,而編譯器不會報錯。
AddItemsToShoppingBasket(); // Works as expectedAddItemsToShoppingBasket(); // Works as expectedAddItemsToShoppingBasket() ' Works as expectedAddItemsToShoppingBasket() ' Works as expected對於具有 params 參數的參數,它被視為可選參數,可以在不傳遞參數的情況下調用。
程式碼範例
建立一個新的控制台應用程式。 打開 Visual Studio,建立一個新專案,並選擇控制台應用程式型別。

現在新增下面的程式碼。
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
List<string> cart = new List<string>();
void AddItemsToShoppingBasket(params string[] samples)
{
for (int i = 0; i < samples.Length; i++)
{
cart.Add(samples[i]);
}
}
// Caller code
Console.WriteLine("Enter the cart items as comma separated values");
var itemsString = Console.ReadLine();
if (itemsString != null)
{
var items = itemsString.Split(",").ToArray();
AddItemsToShoppingBasket(items);
}
AddItemsToShoppingBasket("Sample1", "Sample2");
Console.WriteLine("-------------------------------------------------------");
Console.WriteLine("Display Cart");
foreach (var item in cart)
{
Console.WriteLine(item);
}
}
}using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
List<string> cart = new List<string>();
void AddItemsToShoppingBasket(params string[] samples)
{
for (int i = 0; i < samples.Length; i++)
{
cart.Add(samples[i]);
}
}
// Caller code
Console.WriteLine("Enter the cart items as comma separated values");
var itemsString = Console.ReadLine();
if (itemsString != null)
{
var items = itemsString.Split(",").ToArray();
AddItemsToShoppingBasket(items);
}
AddItemsToShoppingBasket("Sample1", "Sample2");
Console.WriteLine("-------------------------------------------------------");
Console.WriteLine("Display Cart");
foreach (var item in cart)
{
Console.WriteLine(item);
}
}
}Imports System
Imports System.Collections.Generic
Module Program
Sub Main(args As String())
Dim cart As New List(Of String)()
Sub AddItemsToShoppingBasket(ParamArray samples As String())
For i As Integer = 0 To samples.Length - 1
cart.Add(samples(i))
Next
End Sub
' Caller code
Console.WriteLine("Enter the cart items as comma separated values")
Dim itemsString = Console.ReadLine()
If itemsString IsNot Nothing Then
Dim items = itemsString.Split(","c)
AddItemsToShoppingBasket(items)
End If
AddItemsToShoppingBasket("Sample1", "Sample2")
Console.WriteLine("-------------------------------------------------------")
Console.WriteLine("Display Cart")
For Each item In cart
Console.WriteLine(item)
Next
End Sub
End ModuleImports System
Imports System.Collections.Generic
Module Program
Sub Main(args As String())
Dim cart As New List(Of String)()
Sub AddItemsToShoppingBasket(ParamArray samples As String())
For i As Integer = 0 To samples.Length - 1
cart.Add(samples(i))
Next
End Sub
' Caller code
Console.WriteLine("Enter the cart items as comma separated values")
Dim itemsString = Console.ReadLine()
If itemsString IsNot Nothing Then
Dim items = itemsString.Split(","c)
AddItemsToShoppingBasket(items)
End If
AddItemsToShoppingBasket("Sample1", "Sample2")
Console.WriteLine("-------------------------------------------------------")
Console.WriteLine("Display Cart")
For Each item In cart
Console.WriteLine(item)
Next
End Sub
End Module輸出

介紹 IronPDF
IronPDF 是 Iron Software 提供的 C# PDF 程式庫,是一個多功能的程式庫,能夠讀取、寫入並管理 C# 中的 PDF 文件。 它支持各類現代應用開發,如移動端、網站、桌面 Docker 等;它也支持不同操作系統如 Windows、Linux、Unix 等。並不依賴於本機操作系統方法。
IronPDF在HTML到PDF轉換中表現出色,確保精確保留原始佈局和樣式。 對於從基於網頁的內容如報告、發票和文件生成PDF,這是完美的解決方案。 IronPDF支持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 ClassImports 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安裝
可以使用 NuGet 套件管理器控制台或使用 Visual Studio 套件管理器下面的命令來安裝 IronPDF 程式庫。
使用 IronPDF 生成 PDF
現在我們將使用 IronPDF 來自上述範例中生成 PDF 文件。
using System;
using System.Collections.Generic;
using System.Linq;
using IronPdf;
class Program
{
public static void Main()
{
List<string> cart = new List<string>();
void AddItemsToShoppingBasket(params string[] items)
{
for (int i = 0; i < items.Length; i++)
{
cart.Add(items[i]);
}
}
// Take input from console
Console.WriteLine("Enter the cart items as comma separated values");
var itemsString = Console.ReadLine();
// Read the items
if (itemsString != null)
{
var items = itemsString.Split(",").ToArray();
AddItemsToShoppingBasket(items);
}
// Add to cart
AddItemsToShoppingBasket("Sample1", "Sample2");
Console.WriteLine("------------------------------------------------");
Console.WriteLine("Display Cart");
Console.WriteLine("------------------------------------------------");
string name = "Sam";
var count = cart.Count;
string content = $@"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {name}!</h1>
<p>You have {count} items in the cart.</p>
" +
string.Join("\n", cart.Select(x => $"<p>{x}</p>"))
+ @"
</body>
</html>";
// Create a new PDF document
var pdfDoc = new ChromePdfRenderer();
pdfDoc.RenderHtmlAsPdf(content).SaveAs("cart.pdf");
}
}using System;
using System.Collections.Generic;
using System.Linq;
using IronPdf;
class Program
{
public static void Main()
{
List<string> cart = new List<string>();
void AddItemsToShoppingBasket(params string[] items)
{
for (int i = 0; i < items.Length; i++)
{
cart.Add(items[i]);
}
}
// Take input from console
Console.WriteLine("Enter the cart items as comma separated values");
var itemsString = Console.ReadLine();
// Read the items
if (itemsString != null)
{
var items = itemsString.Split(",").ToArray();
AddItemsToShoppingBasket(items);
}
// Add to cart
AddItemsToShoppingBasket("Sample1", "Sample2");
Console.WriteLine("------------------------------------------------");
Console.WriteLine("Display Cart");
Console.WriteLine("------------------------------------------------");
string name = "Sam";
var count = cart.Count;
string content = $@"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {name}!</h1>
<p>You have {count} items in the cart.</p>
" +
string.Join("\n", cart.Select(x => $"<p>{x}</p>"))
+ @"
</body>
</html>";
// Create a new PDF document
var pdfDoc = new ChromePdfRenderer();
pdfDoc.RenderHtmlAsPdf(content).SaveAs("cart.pdf");
}
}Imports Microsoft.VisualBasic
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports IronPdf
Friend Class Program
Public Shared Sub Main()
Dim cart As New List(Of String)()
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
' void AddItemsToShoppingBasket(params string[] items)
' {
' for (int i = 0; i < items.Length; i++)
' {
' cart.Add(items[i]);
' }
' }
' Take input from console
Console.WriteLine("Enter the cart items as comma separated values")
Dim itemsString = Console.ReadLine()
' Read the items
If itemsString IsNot Nothing Then
Dim items = itemsString.Split(",").ToArray()
AddItemsToShoppingBasket(items)
End If
' Add to cart
AddItemsToShoppingBasket("Sample1", "Sample2")
Console.WriteLine("------------------------------------------------")
Console.WriteLine("Display Cart")
Console.WriteLine("------------------------------------------------")
Dim name As String = "Sam"
Dim count = cart.Count
Dim content As String = $"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {name}!</h1>
<p>You have {count} items in the cart.</p>
" & String.Join(vbLf, cart.Select(Function(x) $"<p>{x}</p>")) & "
</body>
</html>"
' Create a new PDF document
Dim pdfDoc = New ChromePdfRenderer()
pdfDoc.RenderHtmlAsPdf(content).SaveAs("cart.pdf")
End Sub
End ClassImports Microsoft.VisualBasic
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports IronPdf
Friend Class Program
Public Shared Sub Main()
Dim cart As New List(Of String)()
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
' void AddItemsToShoppingBasket(params string[] items)
' {
' for (int i = 0; i < items.Length; i++)
' {
' cart.Add(items[i]);
' }
' }
' Take input from console
Console.WriteLine("Enter the cart items as comma separated values")
Dim itemsString = Console.ReadLine()
' Read the items
If itemsString IsNot Nothing Then
Dim items = itemsString.Split(",").ToArray()
AddItemsToShoppingBasket(items)
End If
' Add to cart
AddItemsToShoppingBasket("Sample1", "Sample2")
Console.WriteLine("------------------------------------------------")
Console.WriteLine("Display Cart")
Console.WriteLine("------------------------------------------------")
Dim name As String = "Sam"
Dim count = cart.Count
Dim content As String = $"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {name}!</h1>
<p>You have {count} items in the cart.</p>
" & String.Join(vbLf, cart.Select(Function(x) $"<p>{x}</p>")) & "
</body>
</html>"
' Create a new PDF document
Dim pdfDoc = New ChromePdfRenderer()
pdfDoc.RenderHtmlAsPdf(content).SaveAs("cart.pdf")
End Sub
End Class在上面的程式碼中,我們為購物車商品生成一個 HTML 文件,然後使用 IronPDF 將它保存為 PDF 文件。
輸出

授權(提供免費試用)
IronPDF 在生產環境中需要授權金鑰才能運作。 可以從授權頁面 這裡 獲取試用授權。 將金鑰放置在 appsettings.json 中。
"IronPdf.LicenseKey": "your license key"
提供您的電子郵件 ID 以獲取試用授權發送至您的電子郵件 ID。
結論
C# 中的 params 關鍵字提供了處理需要可變數量參數的方法的靈活途徑。 它簡化了方法調用並使程式碼更具可讀性和可維護性。 配合 IronPDF,這對於任何程式設計師來說都是撰寫乾淨程式碼的強大技能組合。
Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。