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 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 Class
AddItemsToShoppingBasket 方法可以用不同數量的字串參數來調用。 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 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 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 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
如果方法中所定義的 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
}
}
}
Friend Class Program
Shared Sub Main(ByVal args() As String)
' Example 1
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
' public static void AddItemsToShoppingBasket(double total, params string[] items)
' {
' ' Works fine as `params` is the last parameter
' }
' Example 2, error scenario
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
' public static void AddItemsToShoppingBasket(params string[] items, decimal total, int total)
' {
' ' Error: `params` keyword must be the last parameter
' }
End Sub
End Class
僅一個 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 Class
您可以不傳遞任何參數
如果方法有一個 params 關鍵字的參數,則可以在無需任何參數的情況下調用,而編譯器不會報錯。
AddItemsToShoppingBasket(); // Works as expected
AddItemsToShoppingBasket(); // Works as expected
AddItemsToShoppingBasket() ' 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
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim cart As New List(Of String)()
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
' 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")
Dim itemsString = Console.ReadLine()
If itemsString IsNot Nothing Then
Dim items = itemsString.Split(",").ToArray()
AddItemsToShoppingBasket(items)
End If
AddItemsToShoppingBasket("Sample1", "Sample2")
Console.WriteLine("-------------------------------------------------------")
Console.WriteLine("Display Cart")
For Each item In cart
Console.WriteLine(item)
Next item
End Sub
End Class
輸出

介紹 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 Class
安裝
可以使用 NuGet 套件管理器控制台或使用 Visual Studio 套件管理器下面的命令來安裝 IronPDF 程式庫。
Install-Package 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 Class
在上面的程式碼中,我們為購物車商品生成一個 HTML 文件,然後使用 IronPDF 將它保存為 PDF 文件。
輸出

授權(提供免費試用)
IronPDF 在生產環境中需要授權金鑰才能運作。 可以從授權頁面 這裡 獲取試用授權。 將金鑰放置在 appsettings.json 中。
"IronPdf.LicenseKey": "your license key"
提供您的電子郵件 ID 以獲取試用授權發送至您的電子郵件 ID。
結論
C# 中的 params 關鍵字提供了處理需要可變數量參數的方法的靈活途徑。 它簡化了方法調用並使程式碼更具可讀性和可維護性。 配合 IronPDF,這對於任何程式設計師來說都是撰寫乾淨程式碼的強大技能組合。
常見問題
什麼是C#中的'params'關鍵字?
C#中的'params'關鍵字允許方法接受可變數量的參數,簡化了針對不同參數數量的方法調用語法。
在方法簽名中'params'關鍵字如何工作?
在方法簽名中,'params'關鍵字位於參數型別和參數名稱之前,允許方法以陣列方式接受任意數量的該型別參數。
帶有'params'參數的方法可以接受零個參數嗎?
可以,帶有'params'參數的方法可以不帶任何參數調用,因為'params'參數被視為可選的。
在C#中使用'params'的最佳實踐是什麼?
最佳實踐包括將'params'參數放在參數列表的最後,明確指定非'params'參數,並僅在參數數量可以變化時謹慎使用。
C#方法可以有多個'params'參數嗎?
不,C#方法只能有一個'params'參數,且必須是方法簽名中的最後一個參數。
使用'params'如何改善C#中的方法靈活性?
在C#方法中使用'params'允許開發者撰寫更具靈活性的程式碼,能處理動態數量的參數,從而更容易維護和擴展。
如何將'params'關鍵字與C#庫結合用於文件生成?
'params'關鍵字可與C#庫結合,為文件生成任務傳遞靈活數量的參數,例如使用IronPDF建立具有不同內容的PDF。
您如何使用C#庫將HTML轉換為PDF?
您可以使用像IronPDF這樣的C#庫透過RenderHtmlAsPdf方法對HTML字串或RenderHtmlFileAsPdf對HTML文件來轉換HTML為PDF。
在C#中'params'關鍵字的一些常見用例是什麼?
'params'關鍵字的常見用例包括需要處理可變數量輸入的功能,如記錄消息、數學運算或建構字串輸出。
如何在專案中整合C#庫進行PDF操作?
為整合C#庫進行PDF操作,如IronPDF,您可以透過執行dotnet add package [LibraryName]命令安裝它,然後使用其API進行PDF任務。




