文章

C# 使用参数数组

重载,是指在相同的作用域内,声明多个同名的方法。用以对不同类型或数量的参数的参数执行相同的操作。比如,可以求两个 或者三个 int类型数中的最大值,我们可以编写这样的方法实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Util
{
    public static int Max(int num1,int num2)
    {
        return (num1>num2||num1=num2)?num1:num2;
    }
    
    public static int Max(int num1,int num2,int num3)
    {
        int max=num1;
        if(max<num2) max=num2;
        if(max<num3) max=num3;
        return max;
    }
}

显然,当参数数目不确定的时候,重载不是一个好的解决办法,这时候,可以使用数组作为参数传入。以上面的问题为例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Util
{
    public static int Max(int[] paramList)
    {
        if(paramList==null||paramList.length==0)
        {
            throw new ArgumentException("Util.Max:参数值数量不足");
        }
        int currentMax=paramList[0];
        foreach(int i in paramList)
        {
            if(currentMax<i)
            {
                currentMax=i;
            }
        }
        return currentMax;
    }
}

为了使用Max方法判断2个int值得最小值,可以像下面这么写:

1
2
3
4
int[] array=new int[2];
array[0]=first;
array[1]=second;
int max=Util.Max(array);

为了使用Max方法判断2个int值得最小值,可以像下面这么写:

1
2
3
4
5
int[] array=new int[3];
array[0]=first;
array[1]=second;
array[2]=third;
int max=Util.Max(array);

虽然上面的办法避免了大量的重载,但是额外多了很多代码来填充数组,但是如果用 params 关键字来声明一个params数组,一切就OK了,还是用上面的例子,用法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Util
{
    public static int Max(params int[] paramList)
    {
        if(paramList==null||paramList.length==0)
        {
            throw new ArgumentException("Util.Max:参数值数量不足");
        }
        int currentMax=paramList[0];
        foreach(int i in paramList)
        {
            if(currentMax<i)
            {
                currentMax=i;
            }
        }
        return currentMax;
    }
}

这时候如果要求四个int类型的数中的最大值,方法为: Util.Max(first,second,third,fourth); 编译器会自动完成填充数组的过程,再将数组的作为参数传递进去。 那么,对于类型不同的参数,同样可以使用 params object[] 关于params数组,要注意一下几点:

  1. 只能为一位数组使用 params 关键字,不能为多为数组使用,否则编译不能通过。
  2. 不能只依赖 params 关键字来重载一个方法。 params 关键字不构成方法签名的一部分,例如:
    1
    2
    3
    4
    5
    
    //编译时错误:重复的声明
    public static int Max(int[] paramList)
    ...
    public static int Max(params int[] paramList)
    ...
    
  3. 不允许为 params 数组指定 ref 或 out修饰符。
  4. params 数组必须是方法的最后一个参数,没个方法中也只能有一个 params 数组参数。
    1
    2
    
    //编译时错误
    public static int Max(params int[] paramList,int i)
    
  5. 非params方法优先
    1
    2
    3
    4
    
    public static int Max(int first,int second)
    ...
    public static int Max(params int[] paramList)
    ...
    

    对于上面的重载方法,传入两个 int 参数时,调用上面的方法,传入其它任意数量的 int 参数时,调用下面的方法。这样做并非多余,实则起到优化作用。

  6. 有歧义的重载编译不能通过。
    1
    2
    3
    4
    5
    
    //编译时错误
    public static int Max(params int[] paramList)
    ...
    public static int Max(int i, params int[] paramList)
    ...
    

    如上,程序无法分辨调用哪一个方法。

文章可转载,转载请务必注明出处。