这两种方法的确切区别是什么?什么时候使用“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);
}
}
最佳答案
使用 params
,您可以传递零个 个参数,但是对于数组,如果它不是可选,您必须提供该参数。对于例如,您可以在不传递任何参数的情况下调用此方法,并且 args 将为空:
public void Foo(params int[] args) { }
Foo(); // no compile-time error, args will be empty
但是如果你使用数组:
public void Foo(int[] args) { }
Foo(); // error: No overload for 'Foo' takes 0 arguments
除此之外两者没有太大区别。 params
只是一个语法糖。
关于c# - "params"和 "array parameter"有什么区别,应该在什么时候使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27375707/