在实际环境中测试
在生产中测试无水印。
随时随地为您服务。
C# 中的 params 关键字是 .NET 中的一项强大功能,它允许方法接受数量可变的参数。当调用需要不同数量参数的方法时,这可以大大简化语法。在本综合指南中,我们将探讨 C# 中的 params 关键字、其语法、用例和最佳实践。本文稍后将介绍 IronPDF 从 铁软件 并解释如何使用 params 关键字和 IronPDF 生成 PDF。
在 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
"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
将参数放在参数列表的末尾:推荐的做法是将 params 参数放在方法参数列表的末尾。这种做法有助于提高清晰度,减少方法调用过程中的混淆。需要明确值的参数应放在 params 之前,以便有效组织。
明确指定非参数参数:在调用带参数的方法时,确保明确提供非参数参数的值。这种做法可防止歧义,并保证使用必要数量的参数准确调用方法。
谨慎行事,防止歧义:在具有多个重载或相同类型参数的方法中使用参数时,必须保持警惕。编译器可能难以确定要调用的适当方法,从而可能导致歧义错误。
探索其他方法:虽然参数提供了便利,但在某些情况下也要考虑使用其他方法。利用集合,如 List
谨慎应用于相关场景:在参数数量可变且可能在不同方法调用中波动的情况下,应谨慎使用 params。在参数数量不可预测的情况下使用 params,在参数数量固定且已知的情况下避免使用 params。
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
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
数组应与参数方法中定义的类型相同,否则会出现如下错误
// 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
语法错误,因为方法中定义的参数类型不匹配。
在方法签名声明的 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
方法签名中只允许有一个 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
如果一个方法只有带 params 关键字的参数,那么就可以像下面这样不带任何参数地调用该方法,编译器不会抛出错误。
AddItemsToShoppingBasket(); // Works
AddItemsToShoppingBasket(); // Works
AddItemsToShoppingBasket() ' Works
对于任何带 params 参数的参数,都视为可选参数,可以在不传递参数的情况下调用。
创建新的控制台应用程序。打开 Visual Studio,创建新项目并选择控制台应用程序类型。
现在添加以下代码。
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
Iron Software 的 IronPDF C# PDF 库是一个多功能库,可以用 C# 读、写和管理 PDF 文档。它支持各种现代应用程序开发,如移动、网站、桌面、Docker 等。它还支持不同的操作系统,如 Windows、Linux、Unix 等。它不依赖于本地操作系统的方法。
可以使用 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
现在,我们将使用 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
在上述代码中,我们为购物车中的项目生成 HTML 文档,然后使用以下方法将其保存为 PDF 文档 IronPDF.
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"
提供您的电子邮件 ID,试用版许可证就会发送到您的电子邮件 ID。
C# 和 .NET 8 中的 params 关键字为处理需要可变参数数量的方法提供了一种灵活的方法。它简化了方法调用,使代码更具可读性和可维护性。与 IronPDF对于任何程序员来说,这都是编写简洁代码的绝佳技能组合。