Declare a variable number of parameters:
Static int Add(params int[] values)
{
int sum = 0;
if(value != null)
{
for(int x = 0;x<;x++)
sum += values[x];
}
return sum;
}
The above method removes params, which is an ordinary method that accepts an int array and returns the sum of so items in the group.
We can call this: Add(new int[]{1,2,3});
But the reading is not very high, we hope it can be more concise:
Add(1,2,3);
At this time, because of the params keyword, it can be compiled and run.
Params can only be applied to the last one of the method parameters.
When the c# compiler discovers Add(1,2,3), it will first look for whether there is a method that matches Add(int i,int j,int k).
If there is, call it. If there is no, look for whether there is a method defined as Add(params int[] values).
If there is one, save 1, 2, and 3 to an array first, and then call the Add(int[] values) method.
This also shows that CLR knows nothing about the params keyword, and params is only provided to the c# compiler for use.
Copy the codeThe code is as follows:
Static int Add(params int[] values)
{
int sum = 0;
if(value != null)
{
for(int x = 0;x<;x++)
sum += values[x];
}
return sum;
}
The above method removes params, which is an ordinary method that accepts an int array and returns the sum of so items in the group.
We can call this: Add(new int[]{1,2,3});
But the reading is not very high, we hope it can be more concise:
Add(1,2,3);
At this time, because of the params keyword, it can be compiled and run.
Params can only be applied to the last one of the method parameters.
When the c# compiler discovers Add(1,2,3), it will first look for whether there is a method that matches Add(int i,int j,int k).
If there is, call it. If there is no, look for whether there is a method defined as Add(params int[] values).
If there is one, save 1, 2, and 3 to an array first, and then call the Add(int[] values) method.
This also shows that CLR knows nothing about the params keyword, and params is only provided to the c# compiler for use.