我写了这个方法:
static long Sum(params int[] numbers)
{
long result = default(int);
for (int i = 0; i < numbers.Length; i++)
result += numbers[i];
return result;
}
我调用了这样的方法:
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));
我希望编译器在没有任何参数(如Sum()
)的情况下调用方法时显示错误。我怎么能这样做?
答案 0 :(得分:13)
从params
中提取第一个参数以使其成为强制性参数:
static long Sum(int firstSummand, params int[] numbers)
答案 1 :(得分:8)
你可以写
static long Sum(int number1, params int[] numbers)
{
long result = number1;
....
}
但是你会丢失这个选项:
int[] data = { 1, 2, 3 };
long total = Sum(data); // Error, but Sum(0, data) will work.
答案 2 :(得分:2)
编辑:无法使用参数进行编译时间检查...这将为您提供运行时异常...
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;
}
答案 3 :(得分:2)
考虑两个重载:
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;
}
样本用法:
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));
答案 4 :(得分:-4)
params
至少需要一个参数作为array[] arguments
的语法糖。你需要:
Sum(null);
并在您的方法中相应处理null
个案。