[英]method with params
I wrote this method:我写了这个方法:
static long Sum(params int[] numbers)
{
long result = default(int);
for (int i = 0; i < numbers.Length; i++)
result += numbers[i];
return result;
}
I invoked method like this:我调用了这样的方法:
Console.WriteLine(Sum(5, 1, 4, 10));
Console.WriteLine(Sum()); // this should be an error
Console.WriteLine(Sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15));
I want the compiler to shows an error when I call the method without any parameters (like Sum()
).我希望编译器在我调用没有任何参数的方法时显示错误(如
Sum()
)。 How can I do this?我怎样才能做到这一点?
Extract first parameter out of params
to make it mandatory:从
params
中提取第一个参数使其成为强制性参数:
static long Sum(int firstSummand, params int[] numbers)
You could write你可以写
static long Sum(int number1, params int[] numbers)
{
long result = number1;
....
}
But then you would lose this option:但是你会失去这个选项:
int[] data = { 1, 2, 3 };
long total = Sum(data); // Error, but Sum(0, data) will work.
EDIT: Can't get compile time check using params...this will give you a runtime exception...编辑:无法使用参数进行编译时间检查......这会给你一个运行时异常......
static long Sum(params int[] numbers)
{
if(numbers == null || numbers.Length < 2)
{
throw new InvalidOperationException("You must provide at least two numbers to sum");
}
long result = default(int);
for (int i = 0; i < numbers.Length; i++)
result += numbers[i];
return result;
}
Consider two overloads:考虑两个重载:
static long Sum(int head, params int[] tail) {
if (tail == null) throw new ArgumentNullException("tail");
return Sum(new int[] { head }.Concat(tail));
}
static long Sum(IEnumerable<int> numbers) {
if (numbers == null) throw new ArgumentNullException("numbers");
long result = 0;
foreach (var number in numbers) {
result += number;
}
return result;
}
Sample usage:示例用法:
Console.WriteLine(Sum(5, 1, 4, 10));
//Console.WriteLine(Sum()); // Error: No overload for method 'Sum' takes 0 arguments
Console.WriteLine(Sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15));
int[] array = { 42, 43, 44 };
Console.WriteLine(Sum(array));
params
requires at least one argument as its a syntactic sugar for array[] arguments
. params
至少需要一个参数作为array[] arguments
的语法糖。 You need to:你需要:
Sum(null);
and handle the null
case accordingly in your method.并在您的方法中相应地处理
null
案例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.