知识大全 c#中的params关键字的应用

Posted

篇首语:五陵年少金市东,银鞍白马渡春风。本文由小常识网(cha138.com)小编为大家整理,主要介绍了知识大全 c#中的params关键字的应用相关的知识,希望对你有一定的参考价值。

  要接受未知数目的参数 可以使用关键字params 该关键字用于参数列表中 声明参数列表最后面的值 params关键字与数组一起使用

  当值被传递给方法时 编译器首先查看是否有匹配的方法 如果有 则调用该方法 如果没有 编译器将查看是否有包含参数params的方法 如果找到这样的方法 则使用它 编译器将这些值放到一个数组中 并将该数组传递给方法

  下面两个实例

  实例一 使用未知数目的参数

  实例二 使用params来指定多种数据类型

  实例一代码

  using System;

  using System Collections Generic;

  using System Linq;

  using System Text;

  namespace ConsoleAppTest

  

  public class AddEm

  public static long Add(params int[] args)

  int ctr = ;

  long Total = ;

  for (ctr = ; ctr < args Length; ctr++)

  Total += args[ctr];

  

  return Total;

  

  

  class Program

  

  static void Main(string[] args)

  

  long Total = ;

  Total = AddEm Add( );

  Console WriteLine( Total = Total);

  Total = AddEm Add( );

  Console WriteLine( Total = Total);

  Total = AddEm Add( );

  Console WriteLine( Total = Total);

  Total = AddEm Add( );

  Console WriteLine( Total = Total);

  Console Read();

  

  

  

  实例二代码

  using System;

  using System Collections Generic;

  using System Linq;

  using System Text;

  namespace ConsoleAppTest

  

  public class Garbage

  public static void Print(params object[] args)

  int ctr = ;

  for (ctr = ; ctr < args Length; ctr++)

  Console WriteLine( Argument is: ctr args[ctr]);

  

  

  

  class Program

  

  static void Main(string[] args)

  

  long ALong = L;

  decimal ADec = M;

  byte Abyte = ;

  string AString = Cole McCrary ;

  Console WriteLine( First call );

  Garbage Print( );

  Console WriteLine( \\nSecond call );

  Garbage Print();

  Console WriteLine( \\nThird call );

  Garbage Print(ALong ADec Abyte AString);

  Console WriteLine( \\nFourth call );

  Garbage Print(AString is cool ! );

  Console Read();

  

  

cha138/Article/program/net/201311/13747

相关参考