IRONSOFTWAREHOME
開發者更新

C# Params(對於開發者的運行原理)

Jacob Mellor,首席技術官 @ Team Iron
Jacob Mellor
Updated: 2026年4月21日

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
    }
}

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
    }
}

考量與最佳實踐

  • **將 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
    }
}

傳遞一個同型別的逗號分隔參數陣列

AddItemsToShoppingBasket 可以透過在方法呼叫中傳遞變數列表或陣列來調用,如下面所示。

class Program
{
    public static void Main()
    {
        // Example method signature
        AddItemsToShoppingBasket("snacks", "burger", "snacks", "burger", "cold drink"); // Comma separated values
        AddItemsToShoppingBasket("snacks");
    }
}

傳遞已定義型別的陣列

陣列應包含 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

如果方法中所定義的 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 
        }
    }
}

僅一個 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
        }
    }
}

您可以不傳遞任何參數

如果方法有一個 params 關鍵字的參數,則可以在無需任何參數的情況下調用,而編譯器不會報錯。

AddItemsToShoppingBasket(); // Works as expected

對於具有 params 參數的參數,它被視為可選參數,可以在不傳遞參數的情況下調用。

程式碼範例

建立一個新的控制台應用程式。 打開 Visual Studio,建立一個新專案,並選擇控制台應用程式型別。

C# Params(開發者如何使用):圖1 - 建立一個新的控制台應用程式

現在新增下面的程式碼。

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);
        }
    }
}

輸出

C# Params(開發者如何使用):圖2 - 上述程式碼輸出

介紹 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");
    }
}

安裝

可以使用 NuGet 套件管理器控制台或使用 Visual Studio 套件管理器下面的命令來安裝 IronPDF 程式庫。

PM > 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");
    }
}

在上面的程式碼中,我們為購物車商品生成一個 HTML 文件,然後使用 IronPDF 將它保存為 PDF 文件。

輸出

C# Params(如何作用於開發者):圖3 - 從上述程式碼生成的 PDF 輸出

授權(提供免費試用)

IronPDF 在生產環境中需要授權金鑰才能運作。 可以從授權頁面 這裡 獲取試用授權。 將金鑰放置在 appsettings.json 中。

"IronPdf.LicenseKey": "your license key"
JSON

提供您的電子郵件 ID 以獲取試用授權發送至您的電子郵件 ID。

結論

C# 中的 params 關鍵字提供了處理需要可變數量參數的方法的靈活途徑。 它簡化了方法調用並使程式碼更具可讀性和可維護性。 配合 IronPDF,這對於任何程式設計師來說都是撰寫乾淨程式碼的強大技能組合。

Jacob Mellor,首席技術官 @ Team Iron
首席技術官

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

...
閱讀更多

相關文章

Key in blue circle

立即免費取得 30 天試用金鑰。

Your trial license will be sent to your email address

無任何限制。100% 解鎖。無需信用卡。

OR
bullet_checked無需信用卡或建立帳號無任何限制。100% 解鎖。無需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried Iron Suite
預訂您的免費現場演示
Booking Badge

受到全球數百萬工程師的信任

Iron Software的客戶標誌
獲取您的無義務諮詢
填寫以下表格或電子郵件sales@ironsoftware.com
您的詳細資訊將始終保密。
受到全球數百萬工程師的信任
Iron Software的客戶標誌
立即獲取您的30天試用金鑰。
無需信用卡或帳戶建立
C# 用於PDF的NuGet程式庫
使用NuGet安裝

版本: 2026.9

PM > Install-Package IronPdf
nuget.org/packages/IronPdf/
  1. 在解決方案資源管理器,右鍵點選參考,管理NuGet包
  2. 選擇瀏覽並搜尋"IronPdf"
  3. 選擇套件並安裝
C# PDF DLL
下載DLL

版本: 2026.9

或者點擊此處下載Windows安裝程式。

  1. 下載並解壓IronPDF到類似~/Libs的位置,位於您的解決方案目錄中
  2. 在Visual Studio解決方案資源管理器,右鍵點選參考。選擇瀏覽,"IronPdf.dll"

授權從$999起