1 函数参数传递数组
关键字params
class program
{
static int SunVals(param int[] vals)
{
int sum = 0;
foreach(int val in vals)
{
sum += val;
}
return sum;
}
static void Main(string[] args)
{
int sum = SumVals{1,2,3,4,5};
Console.WriteLine("Summed Values = {0}",sum);
Console.ReadKey();
}
}
输出结果为1+2+3+4+5
实例说明关键字params定义函数sumVals(),该函数可以接受任意个int参数(但不接受其他类型的参数)
2 引用参数和值参数
关键字ref
示例一:
static coid ShowDouble(int val)
{
val *= 2;
Console.WriteLine("val doubled = {0}",val);
}
int myNumber = 5;
Console.WriteLine("myNumber = {0}",myNumber);
ShowDouble(myNumber);
Console.WriteLine("myNumber = {0}",myNumber);
输出结果为
myNumber = 5;
val double = 10;
myNumber = 5;
把myNumber作为一个参数,调用ShowDouble()并不影响Main中myNumber的值,即时赋予了val的参数被加倍,myNumber的值也不变。
示例二:
static coid ShowDouble(int ref val)
{
val *= 2;
Console.WriteLine("val doubled = {0}",val);
}
int myNumber = 5;
Console.WriteLine("myNumber = {0}",myNumber);
ShowDouble(ref myNumber);
Console.WriteLine("myNumber = {0}",myNumber);
输出结果为:
myNumber = 5;
val double = 10;
myNumber = 10;
使用ref关键字作为函数参数,函数可能会改变参数的值,所以必须在函数调用中使用“非常量”变量;还必须使用初始化的变量。
关键字out
static int MaxValue(int[] intArray,out int maxIndex)
{
int maxVal = intArray[0];
maxIndex = 0;
for(int i =1;i < intArray.Length;i++)
{
maxVal = intArray[i];
mxIndex = i;
}
return maxVal;
}
int[] myArray = {1,8,3,6,2,5,9,3,0,2};
int maxIndex;
Console.WriteLine("This maximum value in myArray is {0}",MaxValue(myArray,out maxIndex));
Console.WriteLine("The first occurrence of this value is at element {0}",maxIndex + 1);
输出结果为:
The maximum value in myArray is 9
The first occurrence of this value is at element 7