本文目录
在C#中,可以为函数指定一个不定长的参数,这个参数是函数定义中的最后一个参数,这个参数叫做参数数组。
下面是一个例子:
namespace Ch6Ex2{
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, 2, 3, 4, 5);
Console.WriteLine($"Summed Values = {sum}");
Console.ReadKey();
}
}}
函数SumVals
有一个参数数组,即vals
,在定义该参数时,需要使用params
参数。在调用该函数时,可以给参数输入传入多个实参。
可以通过引用传递参数,需要使用ref
关键字。
下面是一个例子:
namespace MyProgram{
class Program
{
static void SwapInts (ref int a, ref int b)
{
int temp = b;
b = a;
a = temp;
}
static void Main(string[] args)
{
int a = 1;
int b = 2;
Console.WriteLine($"a = {a}, b = {b}");
SwapInts(ref a, ref b);
Console.WriteLine($"a = {a}, b = {b}");
Console.ReadKey();
}
}}
这是一个简单的交换两个值的程序,由于函数SwapInts
使用了引用参数,所以可以在函数中修改变量a
和b
的值,需要注意的是,在调用函数时也要使用ref
传递引用参数。
输出参数使用out
关键字,它的效果与引用参数几乎相同,不同点是:
下面是一个例子:
namespace MyProgram{
class Program
{
static int MaxValue (int[] intArray, out int maxIndex)
{
int maxValue = intArray[0];
maxIndex = 0;
for (int i = 0; i < intArray.Length; i++)
{
if (intArray[i] > maxValue)
{
maxValue = intArray[i];
maxIndex = i;
}
}
return maxValue;
}
static void Main(string[] args)
{
int maxIndex;
int[] intArray = { 12, 45, 23, 77, 73 };
int maxValue = MaxValue(intArray, out maxIndex);
Console.WriteLine($"maxValue = {maxValue}, maxIndex = {maxIndex}.");
Console.ReadKey();
}
}}
这个函数将一个数组中最大值的索引作为输出参数,返回最大值。