Optional argument followed by Params [duplicate]

被刻印的时光 ゝ 提交于 2019-12-22 03:19:14

问题


So I see that it's possible to have a method signature where the first parameter provides a default value and the second parameter is a params collection.

What I can't see is a way to actually use the default value of the first argument.

Is it at all possible?

Example method:

void WaitAllTasks(string message = "Running Task.WaitAll", params Task[] tasks);

I initially tried omitting the message parameter when calling the method and also tried using named parameters, which doesn't work with params.

It compiles, but is it possible to use it?


回答1:


I can find three ways of calling the method without specifying a value for the first parameter:

using System;

class Test
{
    static void PrintValues(string title = "Default",
                            params int[] values)
    {
        Console.WriteLine("{0}: {1}", title, 
                          string.Join(", ", values));
    }

    static void Main()
    {
        // Explicitly specify the argument name and build the array
        PrintValues(values: new int[] { 10, 20 });
        // Explicitly specify the argument name and provide a single value
        PrintValues(values: 10);
        // No arguments: default the title, empty array
        PrintValues();
    }
}

I haven't found a way of specifying multiple values without explicitly building the array though...



来源:https://stackoverflow.com/questions/12747117/optional-argument-followed-by-params

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!