在实际环境中测试
在生产中测试无水印。
随时随地为您服务。
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
在相关场景中明智地应用:在参数数量可变且可能在不同的方法调用中波动的场景中,明智地部署参数。 将其用在参数数量不可预知的情况下,并避免在参数数量固定且已知时使用。
可以通过调用一维数组来使用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 参数。
方法签名中的参数应定义在最后,之后不允许有参数。 这样定义会导致编译错误。
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
IronPDF C# PDF库来自Iron Software,是一个多功能的库,可以在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
现在我们将使用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对于任何程序员来说,这都是编写简洁代码的绝佳技能组合。