"params"和"array parameter"有什么区别?什么时候应该使用它?

cha*_*les 2 c#

这两种方法之间的确切区别是什么?何时使用"params"以及何时使用数组参数?回复将不胜感激.

// passing array to a method
class Program
{
    static void printarray(int[] newarray)
    {
        int i,sum=0;
        Console.Write("\n\nYou entered:\t");
        for (i = 0; i < 4; i++)
        {
            Console.Write("{0}\t", newarray[i]);
            sum = sum + newarray[i];
        }
        Console.Write("\n\nAnd sum of all value is:\t{0}", sum);
        Console.ReadLine();
    }
    static void Main(string[] args)
    {
        int[] arr = new int[4];
        int i;
        for (i = 0; i < 4; i++)
        {
            Console.Write("Enter number:\t");
            arr[i] = Convert.ToInt32(Console.ReadLine());
        }
        // passing array as argument
        Program.printarray(arr);
        }
    }
}
//using parameter arrays
public class MyClass
{
public static void UseParams(params int[] list)
{
    for (int i = 0; i < list.Length; i++)
    {
        Console.Write(list[i] + " ");
    }
    Console.WriteLine();
}
static void Main()
{ 
    UseParams(1, 2, 3, 4);
    int[] myIntArray = { 5, 6, 7, 8, 9 };
    UseParams(myIntArray);      
}
}
Run Code Online (Sandbox Code Playgroud)

Sel*_*enç 6

使用params你可以传递零个或多个参数,但是对于数组,如果它不是可选的,你必须激活该参数.例如,你可以在不传递任何参数的情况下调用此方法,并且args将为空:

public void Foo(params int[] args) { }

Foo(); // no compile-time error, args will be empty
Run Code Online (Sandbox Code Playgroud)

但是如果你使用一个数组:

public void Foo(int[] args) { }

Foo(); // error: No overload for 'Foo' takes 0 arguments
Run Code Online (Sandbox Code Playgroud)

否则两者之间没有太大区别.params只是一个语法糖.