开发者

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 paramete开发者_如何学Crs (like Sum()). How can I do this?


Extract first parameter out of params to make it mandatory:

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. You need to:

Sum(null);

and handle the null case accordingly in your method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜