Today's content is mainly a parameter array, C # allows the function to specify a (only one) specific parameter, which must be the last parameter in the function definition, become a parameter array.
parameter arrays can call functions with variable numbers of parameters, which can be defined using the params keyword.
When you define a function that uses a parameter array, you use the following code:
Static<returntype><functionname> (<p1Type><p1Name>,..., params<type>[]<name>)
{
...
Return<returntype>
}
The function can be called using the following code:
<functionName> (<p1>,..., <val1>,<val2>,...)
Where <val1> and <val2> are all types of values that are used to initialize <name> arrays. The number of parameters you can specify is almost unlimited. The only limitation is that they all have to be <type>, and you can even specify no parameters at all.
This makes the parameter array particularly suitable for specifying additional information for functions to be used during processing.
For example, Jiading has a Getword () whose first argument is a string value and returns the first word in a string:
String Firstword=getword ("This is a sentence.");
Where FirstWord is given the string this. You can add a params parameter in Getword () to select another word to return based on its index.
String Firstword=getword ("This is a sentence.", 2);
Assuming that the first word count is 1, the FirstWord is given a string is.
You can also limit the number of characters returned in the third parameter, which is also done by the params.
Stirng Firstword=getword ("This is a sentence.", 4, 3);
At this point, FirstWord is given the string Sen.
Class Program
{
static int sumvals (params int[] vals)
{
int sum=0;
foreach (int val in vals)
{
Sum+=val;
}
return sum;
}
static void Main (string[] args)
{
int sum=sumvals (1,5,2,9,8);
Console.WriteLine ("Summed values={0}", sum);
Console.readkey ();
}
}
which
static int sumvals (params int[] vals)
{
int sum=0;
foreach (int val in vals)
{
Sum+=val;
}
return sum;
}
Define the function sumvals with the keyword params, which can accept any int parameter (but not other types of arguments)
Feel this is still not very good understanding, tomorrow also need to strengthen.
C # Learning Day Sixth