// Pass in a comma-delimited list of doubles...
double average;
average = CalculateAverage(4.0, 3.2, 5.7, 64.22, 87.2);
Console.WriteLine("Average of data is: {0}", average);
// ...or pass an array of doubles.
double[] data = { 4.0, 3.2, 5.7 };
average = CalculateAverage(data);
Console.WriteLine("Average of data is: {0}", average);
// Average of 0 is 0!
Console.WriteLine("Average of data is: {0}", CalculateAverage());
Console.ReadLine();
}
■
Note
To avoid any ambiguity, C# demands a method only support a single
params
argument, which must be
the final argument in the parameter list.
As you might guess, this technique is nothing more than a convenience for the caller, given that
the array is created by the CLR as necessary. By the time the array is within the scope of the method
being called, you are able to treat it as a full-blown .NET array that contains all the functionality of
the System.Array base class library type. Figure 4-3 illustrates the output.
Figure 4-3.
The params keyword allows you to build methods with a variable number of arguments.
Do'stlaringiz bilan baham: |