Initializing a string array in a method call as a parameter in C#

后端 未结 4 1516
说谎
说谎 2021-01-17 22:53

If I have a method like this:

public void DoSomething(int Count, string[] Lines)
{
   //Do stuff here...
}

Why can\'t I call it like this?<

4条回答
  •  说谎
    说谎 (楼主)
    2021-01-17 23:40

    If DoSomething is a function that you can modify, you can use the params keyword to pass in multiple arguments without creating an array. It will also accept arrays correctly, so there's no need to "deconstruct" an existing array.

    class x
    {
        public static void foo(params string[] ss)
        {
            foreach (string s in ss)
            {
                System.Console.WriteLine(s);
            }
        }
    
        public static void Main()
        {
            foo("a", "b", "c");
            string[] s = new string[] { "d", "e", "f" };
            foo(s);
        }
    }
    

    Output:

    $ ./d.exe 
    a
    b
    c
    d
    e
    f
    

提交回复
热议问题