参数数组允许特定类型的零个或多个实参对应一个特定的形参。
参数数组的重点如下:
- 在一个参数列表中只能有一个参数数组
- 如果有,它必须是列表中的最后一个
- 由参数数组表示的所有参数必须是同一类型
声明一个参数数组需要注意:
- 在数据类型前使用params修饰符
- 在数据类型后放置一组空的方括号
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
public delegate double Calc(double x, double y); //定义委托
class MyClass
{
public void ListInts(int a, params int[] inVals)
{
Console.WriteLine("input number is {0}", a);
if ((inVals != null) && (inVals.Length != 0))
{
for (int i = 0; i < inVals.Length; i++)
{
inVals[i] = inVals[i] * 10;
Console.WriteLine("{0}", inVals[i]);
}
}
}
}
class Program
{
static void Main(string[] args)
{
//参数数组:传入值类型并不会并改变
//int first = 5, second = 6, third = 7;
//MyClass mc = new MyClass();
//mc.ListInts(first, second, third);
//Console.WriteLine("{0} {1} {2}", first, second, third);
//参数数组:传入引用烈性会被改变
int[] arr = new int[] { 5, 6, 7};
MyClass mc = new MyClass();
mc.ListInts(3, arr);
foreach (var item in arr)
{
Console.WriteLine(item);
}
}
}
}
关于参数数组,需要注意的一点是:当数组在堆中被创建时,实参的值被复制到数组中。这样,它们像值参数。
- 如果数组参数是值类型,那么值被复制,实参方法在内部不受影响
- 如果数组参数是引用类型,那么引用被复制,实参引用的对象在方法内部会受到影响