.NET幫助 C# Params(對於開發者的運行原理) Curtis Chau 更新日期:6月 22, 2025 Download IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article C#中的params關鍵字是一個強大功能,可以讓方法接受可變數量的參數,在.NET中運作。 這可以大大簡化呼叫需要不同數量參數的方法時的語法。 在這份全面的指南中,我們將探討C#中的params關鍵字、其語法、用例及最佳做法。 Later in this article, we will introduce the IronPDF library from Iron Software and explain how to use the params keyword and IronPDF to generate PDFs. 什麼是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 $vbLabelText $csharpLabel 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 $vbLabelText $csharpLabel 考量及最佳做法 將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 $vbLabelText $csharpLabel 傳入相同類型的逗號分隔數組的參數 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 $vbLabelText $csharpLabel 傳入定義類型的數組 數組應包含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 $vbLabelText $csharpLabel 若從方法中定義的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 $vbLabelText $csharpLabel 僅允許一個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 $vbLabelText $csharpLabel 可以不傳遞參數 若一個方法含有params關鍵字的參數,可以在不傳遞任何參數的情況下呼叫,也不會引發編譯器錯誤。 AddItemsToShoppingBasket(); // Works as expected AddItemsToShoppingBasket(); // Works as expected AddItemsToShoppingBasket() ' Works as expected $vbLabelText $csharpLabel 對於任何具有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 $vbLabelText $csharpLabel 輸出 介紹IronPDF Iron Software提供的IronPDF C# PDF函式庫是一個多功能函式庫,可在C#中讀取、寫入和管理PDF文檔。 它支持各種現代應用開發,例如移動、網站、桌面、Docker等。並且還支持不同的作業系統,例如Windows、Linux、Unix等。它不依賴於本機作業系統方法。 IronPDF 在HTML 到 PDF轉換方麵表現出色,確保準確保持原始佈局和樣式。 它非常適合從網路內容生成 PDF,如報告、發票和文檔。 支持 HTML 文件、URL 和原始 HTML 字串的 IronPDF 可以輕鬆生成高質量的 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 $vbLabelText $csharpLabel 安裝 可以使用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 $vbLabelText $csharpLabel 在上述代碼中,我們正在為購物車項目生成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# 庫將 HTML 轉換為 PDF,通過使用方法如 RenderHtmlAsPdf 對於 HTML 字符串或 RenderHtmlFileAsPdf 對於 HTML 文件。 在 C# 中 'params' 關鍵字的一些常見使用案例是什麼? 常見的使用案例包括需要處理可變數量輸入的方法,例如記錄消息、數學運算或構建字符串輸出。 如何在項目中集成 C# 庫以進行 PDF 操作? 要集成 C# 庫用於 PDF 操作,如 IronPDF,您可以使用命令 dotnet add package [LibraryName] 通過 NuGet 安裝,然後使用其 API 來執行 PDF 任務。 Curtis Chau 立即與工程團隊聊天 技術作家 Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。 相關文章 更新日期 9月 4, 2025 RandomNumberGenerator C# 使用RandomNumberGenerator C#類可以幫助將您的PDF生成和編輯項目提升至新水準 閱讀更多 更新日期 9月 4, 2025 C#字符串等於(它如何對開發者起作用) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 更新日期 8月 5, 2025 C#開關模式匹配(對開發者來說是如何工作的) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 C# PostgreSQL(對於開發者的運行原理)C# Enum(對於開發者的運行...