“参数”和“数组参数”有什么区别,什么时候应该使用它
本文关键字:参数 什么时候 什么 数组 数组参数 区别 | 更新日期: 2023-09-27 18:33:49
这两种方法之间的确切区别是什么?何时使用"参数"以及何时使用数组参数?如能得到答复,将不胜感激。
// 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
可以传递零个或多个参数,但对于数组,如果该参数不是可选的,则必须启动该参数。例如,您可以在不传递任何参数的情况下调用此方法,参数将为空:
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
只是一种句法糖。
除了塞尔曼的回答, 使用params
时还有一些明显但很小的限制:
根据 MS C# 参考
方法声明中的 params 关键字后不允许使用其他参数,并且方法声明中只允许一个 params 关键字。
这是因为编译器很难识别哪个参数属于哪个参数。编译器也会抱怨,如果你在params
之前有正常的参数
params
参数必须是正式参数列表中的最后一个参数。
例如,这是不允许的:
public void Foo(params int[] args,int value) { }
添加到前两个答案。如果我们有方法
calculate(params int[] b)
然后可以使用calculate(1,2,3)
调用它
现在,如果您使用整数数组calculate(int[] b)
.您将无法像这样调用函数 calculate(1,2,3)
.
-
Arrays
需要将至少 1 个参数传递给方法才能工作。 -
params
可以在方法中没有参数的情况下工作。 -
方法声明中的
params
关键字后不允许使用其他参数,并且方法声明中只允许一个params
关键字。static int test(params string[] test1) { return test1.Length; }
- 使用一些参数调用该方法。
Console.WriteLine($"'"params'" got {test("Japan", "Germany", "Maldives")} strings in the row."); // returns 3
- 调用不带参数的方法。数组做不到。
Console.WriteLine($"'"params'" got {test()} strings in the row."); // returns 0