Creating methods with infinite parameters?

两盒软妹~` 提交于 2019-12-02 17:23:33
Klaus Byskov Pedersen

With the params keyword.

Here is an example:

    public int SumThemAll(params int[] numbers)
    {
        return numbers.Sum();
    }

    public void SumThemAllAndPrintInString(string s, params int[] numbers)
    {
        Console.WriteLine(string.Format(s, SumThemAll(numbers)));
    }

    public void MyFunction()
    {
        int result = SumThemAll(2, 3, 4, 42);
        SumThemAllAndPrintInString("The result is: {0}", 1, 2, 3);
    }

The code shows various things. First of all the argument with the params keyword must always be last (and there can be only one per function). Furthermore, you can call a function that takes a params argument in two ways. The first way is illustrated in the first line of MyFunction where each number is added as a single argument. However, it can also be called with an array as is illustrated in SumThemAllAndPrintInString which calls SumThemAll with the int[] called numbers.

Use the params keyword. Usage:

public void DoSomething(int someValue, params string[] values)
{
    foreach (string value in values)
        Console.WriteLine(value);
}

The parameter that uses the params keyword always comes at the end.

A few notes.

Params needs to be marked on an array type, like string[] or object[].

The parameter marked w/ params has to be the last argument of your method. Foo(string input1, object[] items) for example.

use the params keyword. For example

static void Main(params string[] args)
{
    foreach (string arg in args)
    {
        Console.WriteLine(arg);
    }
}
Faizan S.

You can achieve this by using the params keyword.

Little example:

public void AddItems(params string[] items)
{
     foreach (string item in items)
     { 
         // Do Your Magic
     }
}
    public static void TestStrings(params string[] stringsList)
    {
        foreach (string s in stringsList){ } 
            // your logic here
    }
 public string Format(params string[] value)
 {
            // implementation
 }

The params keyword is used

function void MyFunction(string format, params object[] parameters) {

}

Instad of object[] you can use any type your like. The params argument always has to be the last in the line.

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