.NET 幫助

C# 參數(它是如何為開發人員工作的)

發佈 2024年3月26日
分享:

C# 中的 params 關鍵字是 .NET 中一個強大的功能,允許方法接受可變數量的參數。這可以大大簡化調用需要不同數量參數的方法時的語法。在這個綜合指南中,我們將探索 C# 中的 params 關鍵字、其語法、使用情境和最佳實踐。在本文稍後,我們將介紹 IronPDF 圖書館由 Iron Software 並解釋如何使用參數關鍵字和 IronPDF 來生成 PDF。

什麼是C#的Params參數類型?

在C#的領域中,方法通常遵循一組預定的參數。然而,有些情況下,可能會不確定方法將接收的精確參數數量。此時,可以使用“params”關鍵字,這是一種能夠指定方法參數並容納一組參數的解決方案。當開發人員不確定提前會有多少參數時,這一功能非常寶貴,它使得在方法聲明中,能夠傳遞數量不確定或可選的參數,而且所有的類型都一致。

public class ParamsExample
{
    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)
{
  // ....
}
public static void AddItemsSumToShoppingBasket(params int [] sum) // params int
{
  // ....
}
public class ParamsExample
{
    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)
{
  // ....
}
public static void AddItemsSumToShoppingBasket(params int [] sum) // params int
{
  // ....
}
Public Class ParamsExample
	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)
  ' ....
End Sub
Public Shared Sub AddItemsSumToShoppingBasket(ParamArray ByVal sum() As Integer) ' params int
  ' ....
End Sub
VB   C#

"AddItemsToShoppingBasket"方法可以用可變數量的字串參數來調用。params物件關鍵字通過允許開發人員直接傳遞可選參數,而不用顯式創建數組輸入,簡化了方法調用的語法。

class Program {
AddItemsToShoppingBasket("cake", "pizza", "cold drink");
AddItemsToShoppingBasket("snacks", "burger");
AddItemsToShoppingBasket(); // Valid with zero parameters default value
}
class Program {
AddItemsToShoppingBasket("cake", "pizza", "cold drink");
AddItemsToShoppingBasket("snacks", "burger");
AddItemsToShoppingBasket(); // Valid with zero parameters default value
}
Friend Class Program
AddItemsToShoppingBasket("cake", "pizza", "cold drink")
AddItemsToShoppingBasket("snacks", "burger")
AddItemsToShoppingBasket() ' Valid with zero parameters default value
End Class
VB   C#

考量與最佳實踐

在參數列表的末尾放置 Params 參數:建議的做法是將 params 參數放在方法參數列表的結尾。這種做法有助於清晰度,減少在調用方法時的混淆。需要明確值的參數應該排在 params 之前,以便於有效組織。

明確指定非 params 的參數:在調用帶有 params 的方法時,請確保明確提供非 params 參數的值。這種做法可以防止歧義,並保證以所需數量的參數正確調用方法。

謹慎防止歧義:在使用多重重載或具有相同類型參數的方法中使用 params 時,謹慎是關鍵。編譯器可能會在確定要調用的合適方法時掙扎,可能會導致歧義錯誤。

探索替代方法:雖然 params 提供了便利,在某些情境下請考慮替代方法。例如使用 List 等集合。可以更適合增強功能或在傳遞命名參數與您的目標一致時使用。

謹慎應用於相關場景:在參數數量可變且在不同方法調用中可能波動的場景中謹慎地部署參數。將其用於參數數量不可預測的情況,避免在參數數量是固定和已知的情況下使用。

一維陣列作為參數類型

AddItemsToShoppingBasket 也可以通過使用一維陣列來調用。

// example
class Program {
public static void main()
{
var items = [] {"cold drink", "snack", "roll", }; // 1D string array
AddItemsToShoppingBasket(items); // works
AddItemsToShoppingBasket( "cold drink", "coke", "roll",); // same as above line
}
}
// example
class Program {
public static void main()
{
var items = [] {"cold drink", "snack", "roll", }; // 1D string array
AddItemsToShoppingBasket(items); // works
AddItemsToShoppingBasket( "cold drink", "coke", "roll",); // same as above line
}
}
' example
Friend Class Program
Public Shared Sub main()
Dim items = () {"cold drink", "snack", "roll"} ' 1D string array
AddItemsToShoppingBasket(items) ' works
AddItemsToShoppingBasket("cold drink", "coke", "roll",) ' same as above line
End Sub
End Class
VB   C#

傳遞逗號分隔的相同類型參數數組

AddItemsToShoppingBasket 也可以通過在方法調用中傳遞變量的列表/數組來調用,如下所示。

// example method signature
class Program {
AddItemsToShoppingBasket("snacks", "burger", "snacks", "burger", "cold drink"); // comma separated values
AddItemsToShoppingBasket("snacks"); 
}
// example method signature
class Program {
AddItemsToShoppingBasket("snacks", "burger", "snacks", "burger", "cold drink"); // comma separated values
AddItemsToShoppingBasket("snacks"); 
}
' example method signature
Friend Class Program
AddItemsToShoppingBasket("snacks", "burger", "snacks", "burger", "cold drink") ' comma separated values
AddItemsToShoppingBasket("snacks")
End Class
VB   C#

傳遞定義類型的數組

數組應包含與 params 方法中定義相同的類型,否則將拋出如下錯誤

// example
AddItemsToShoppingBasket("snacks",2,"burger"); // error 
AddItemsToShoppingBasket(2,3,4); // error as params type is string
// example
AddItemsToShoppingBasket("snacks",2,"burger"); // error 
AddItemsToShoppingBasket(2,3,4); // error as params type is string
' example
AddItemsToShoppingBasket("snacks",2,"burger") ' error
AddItemsToShoppingBasket(2,3,4) ' error as params type is string
VB   C#

由於方法中定義的參數類型不匹配,發生語法錯誤。

總是方法中的最後一個參數

在方法簽名宣告中,params 參數之後不允許有其他附加參數,而且在方法參數宣告中只允許有一個 params 參數。

方法簽名應將 params 定義在最後,之後不能有其他參數。如此定義會導致編譯錯誤。

class program {
static void Main(string [] args){
// example 1
   public static void AddItemsToShoppingBasket(double total, params string [] items)
   {
     // ....
   } // This works
}
}
example 2
static void Main(string [] args){
   public static void AddItemsToShoppingBasket(double total, int total, params string [] items)
   {
     // ....
   } // This works
}
// example 3 error scenario
static void Main(string [] args){
   public static void AddItemsToShoppingBasket(params string [] items, decimal total, int total)
   {
     // error
   } // params keyword is defined as first parameter, needs to be at the last.
}
class program {
static void Main(string [] args){
// example 1
   public static void AddItemsToShoppingBasket(double total, params string [] items)
   {
     // ....
   } // This works
}
}
example 2
static void Main(string [] args){
   public static void AddItemsToShoppingBasket(double total, int total, params string [] items)
   {
     // ....
   } // This works
}
// example 3 error scenario
static void Main(string [] args){
   public static void AddItemsToShoppingBasket(params string [] items, decimal total, int total)
   {
     // error
   } // params keyword is defined as first parameter, needs to be at the last.
}
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)
'   {
'	 ' ....
'   } ' This works
End Sub
End Class
example 2 Shared Sub Main(ByVal args() As String)
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'   public static void AddItemsToShoppingBasket(double total, int total, params string [] items)
'   {
'	 ' ....
'   } ' This works
End Sub
' example 3 error scenario
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, decimal total, int total)
'   {
'	 ' error
'   } ' params keyword is defined as first parameter, needs to be at the last.
End Sub
VB   C#

只能有一個 params 關鍵字

在方法簽名中只允許一個 params 參數。如果在方法簽名中找到多於一個的 params 關鍵字,編譯器將拋出錯誤。

//only one params keyword example
class Program {
static void Main(string [] args){
public static void AddItemsToShoppingBasket(params string [] items, params string [] quantity)
{
} // Compiler error, This does not work. 
}
}
//only one params keyword example
class Program {
static void Main(string [] args){
public static void AddItemsToShoppingBasket(params string [] items, params string [] quantity)
{
} // Compiler error, This does not work. 
}
}
'only one params keyword example
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, This does not work.
End Sub
End Class
VB   C#

你可以不傳遞任何參數

如果一個方法只有使用 params 關鍵字的參數,那麼它可以在不傳遞任何參數的情況下被調用,如下所示,編譯器不會拋出錯誤。

AddItemsToShoppingBasket(); // Works
AddItemsToShoppingBasket(); // Works
AddItemsToShoppingBasket() ' Works
VB   C#

任何帶有參數的參數被視為可選參數,可以在不傳遞參數的情況下調用。

代碼範例

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

C# 參數(針對開發人員的工作原理):圖 1 - 創建一個新的控制台應用程序

現在添加以下代碼。

class Program {
Console.WriteLine("Params demo");
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
static void Main(string [] args) {
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);
}
}
}
class Program {
Console.WriteLine("Params demo");
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
static void Main(string [] args) {
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);
}
}
}
Friend Class Program
Console.WriteLine("Params demo")
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
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'static void Main(string [] args)
'{
'Console.WriteLine("Enter the cart items as comma separated values");
'var itemsString = Console.ReadLine();
'if (itemsString != Nothing)
'{
'	var items = itemsString.Split(",").ToArray();
'	AddItemsToShoppingBasket(items);
'}
'AddItemsToShoppingBasket("Sample1", "Sample2");
'Console.WriteLine("-------------------------------------------------------");
'Console.WriteLine("Display Cart");
'foreach (var item in cart)
'{
'	Console.WriteLine(item);
'}
'}
End Class
VB   C#

輸出

C# 參數(開發者如何使用):圖 2 - 上述代碼輸出

介紹 IronPDF

Iron Software 的 IronPDF C# PDF 庫是一個多功能的庫,可以在 C# 中讀取、寫入和管理 PDF 文件。它支持各種現代應用程序的開發,如移動、網站、桌面、Docker 等。並且支持不同的操作系統,如 Windows、Linux、Unix 等。它不依賴於本地操作系統方法。

安裝

IronPDF 庫可以使用... 安裝 NuGet 在封裝管理員主控台使用以下命令或使用 Visual Studio 封裝管理員。

dotnet add package IronPdf
dotnet add package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'dotnet add package IronPdf
VB   C#

使用 IronPDF 生成 PDF

現在我們將使用 IronPDF 從上述示例生成 PDF 文件。

class program
{
public static void main()
{
Console.WriteLine("IronPDF to generate the PDF document for Params Example");
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 seperated 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");
}
}
class program
{
public static void main()
{
Console.WriteLine("IronPDF to generate the PDF document for Params Example");
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 seperated 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

Friend Class program
Public Shared Sub main()
Console.WriteLine("IronPDF to generate the PDF document for Params Example")
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 seperated 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
VB   C#

在上面的程式碼中,我們正在為購物車項目生成HTML文件,然後將其保存為PDF文件,使用 IronPDF.

輸出

C# 參數(開發人員如何使用):圖 3 - 上述程式碼的 PDF 輸出

授權 (免費試用)

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

"IronPdf.LicenseKey": "your license key"
"IronPdf.LicenseKey": "your license key"
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'"IronPdf.LicenseKey": "your license key"
VB   C#

請提供您的電子郵件地址以獲取試用許可證,該許可證將發送到您的電子郵件地址。

結論

在 .NET 8 中使用 C# 的 params 關鍵字提供了一種靈活的方法來處理需要可變數參數的方法。它簡化了方法調用,使代碼更易讀且更易於維護。 IronPDF,這對於任何程式設計師來說都是撰寫乾淨程式碼的絕佳技能組合。

< 上一頁
C# PostgreSQL(如何為開發人員運作)
下一個 >
C# 列舉 (開發人員如何使用)

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

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