params

博客介绍了params关键字,它是声明函数时的关键字,与ref、out不同。其最大好处是可在不知参数个数的情况下动态调用函数,如UseParams函数可传入不同数量的参数。同时提到方法声明中params后不能有其他参数,且只能有一个params关键字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个东西也是声明函数的时候的一个关键字,但是和ref,out不太一样。

这个东西最大的好处就是,可以不知道这种类型的参数的个数,而动态的调用他。

比如这个函数,下面的这两种的usage都可以。

UseParams(1, 2, 3);
UseParams(1, 2, 3,4 ) ;

The params keyword lets you specify a method parameter that takes an argument where the number of arguments is variable.

No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.

Example
// cs_params.cs
using System;
public class MyClass 
{

   public static void UseParams(params int[] list) 
   {
      for ( int i = 0 ; i < list.Length ; i++ )
         Console.WriteLine(list[i]);
      Console.WriteLine();
   }

   public static void UseParams2(params object[] list) 
   {
      for ( int i = 0 ; i < list.Length ; i++ )
         Console.WriteLine(list[i]);
      Console.WriteLine();
   }

   public static void Main() 
   {
      UseParams(1, 2, 3);
      UseParams2(1, 'a', "test"); 

      int[] myarray = new int[3] {10,11,12};
      UseParams(myarray);
   }
}
Output
1
2
3

1
a
test

10
11
12
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值