c variable number parameter params instances

  • 2020-05-17 05:22:50
  • OfStack

Generally speaking, the number of parameters is fixed, and parameters defined as cluster types can achieve the purpose of variable number of parameters, but NET provides a more flexible mechanism for variable number of parameters, which is the use of the params modifier. The advantage of a variable number of parameters is that it can be easily implemented in some cases where the number of parameters is uncertain, such as calculating the weighted sum of any number, linking any string to 1 string, and so on. Here's an example:

 
public class Test2 
{ 
public static void Main() 
{ 
ShowName(" batman "); 
ShowName(" wang ", " small 6"); 
} 
public static void ShowName(params string[] names) 
{ 
foreach (string name in names) 
{ 
Console.WriteLine(name); 
} 
} 
} 


Note:
1. The parameters modified by params must be 1-dimensional array.
2. The parameter array modified by params can be of any type, as long as the array type is set to object.
3. params must be at the end of the parameter list and can only be used once.

Related articles: