Creating methods with infinite parameters?

后端 未结 8 1619
再見小時候
再見小時候 2021-01-31 13:44

In C# you can do this:

foo = string.Format(\"{0} {1} {2} {3} ...\", \"aa\", \"bb\", \"cc\" ...);

This method Format() accepts in

相关标签:
8条回答
  • 2021-01-31 14:43

    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.

    0 讨论(0)
  • 2021-01-31 14:44
     public string Format(params string[] value)
     {
                // implementation
     }
    

    The params keyword is used

    0 讨论(0)
提交回复
热议问题