以前从来没有接触过params关键字,一直很好奇一些类型的string.Format(...)方法具有无限长的方法参数。有时候被逼用数组代替。发现params关键字有,编写不定长参数的方法很简单

 

就是在原先需要不定长常数类型钱加上params就可以了。

 

例如

public int Sum(params int[] narray)

{

    int ret=0;

    foreach(int n in narray)

    {

        ret+=n;

    }

   return ret;

}

 

方法调用:

int xSum=Sum(1,2,3,4,5,6,7,8.....);

 

优点,减少不必要的数组组建,内存开销,代码更直观。

相关文章:

  • 2021-07-06
  • 2021-10-10
  • 2022-12-23
  • 2021-08-14
  • 2022-12-23
  • 2022-12-23
  • 2022-01-26
猜你喜欢
  • 2021-08-19
  • 2021-11-07
  • 2022-01-24
  • 2022-12-23
  • 2022-12-23
  • 2021-07-28
相关资源
相似解决方案