params 修饰符
《C# 与 .NET 4高级程序设计》读书笔记
params关键字可以把可变数量的相同类型参数作为单个逻辑参数传给方法。
调用者可以传入强类型数组或以逗号分隔的项列表。
using System; namespace Test { class Program { static double CalculateAverage(params double[] values) { Console.WriteLine("You sent me {0} doubles.", values.Length); double sum = 0; if (values.Length == 0) { return sum; } for (int i = 0; i < values.Length; i++) { sum += values[i]; } return (sum / values.Length); } static void Main(string[] args) { Console.WriteLine("***** Fun with Methods *****"); // 传递一个以逗号分隔的double型数的列表 double average; average = CalculateAverage(4.0, 3.2, 5.7, 64.2, 87.2); Console.WriteLine("Average of data is: {0}", average); //传递一个double型的数组 double[] data = { 4.0, 3.2, 5.7 }; average = CalculateAverage(data); Console.WriteLine("Average of data is: {0}", average); // 0的平均值是0 Console.WriteLine("Average of data is: {0}", CalculateAverage()); Console.ReadLine(); } } }