How to pass an array and a single element to a multiple argument method?

后端 未结 4 1413
你的背包
你的背包 2021-01-18 08:59

Example:

public void foo(params string[] s) { ... }

We can call this method with:

a) foo(\"test\", \"test2\", \"test3\") //         


        
相关标签:
4条回答
  • 2021-01-18 09:11

    Only the last parameter of a method can be a parameter array (params) so you can't pass more than one variable into a method whose signature only takes in params.

    Therefore what you're trying to do in C isn't possible and you have to add that string into an array, or create an overload that also takes a string parameter first.

    public void foo(string firstString, params string[] s)
    {
    } 
    
    0 讨论(0)
  • 2021-01-18 09:23

    I think you're assuming that string[] s accepts a single string argument as well as an array of strings, which it does not. You can achieve this via.

    public static void Test(string[] array, params string[] s)
    {
    
    }
    

    (Remember params has to be the last argument)

    And then to invoke:

    Test(new string[]{"test", "test2", "test3"}, "test");
    

    Notice how the array is passed in first, and then the argument that is passed as params.

    0 讨论(0)
  • 2021-01-18 09:24

    Just add your string to the array:

    var newArray = new string[oldArray.length+1];
    newArray[0]=yourString;
    oldArray.CopyTo(newArray, 1);
    
    foo(newArray);
    
    0 讨论(0)
  • 2021-01-18 09:30

    While you can solve this without using an extension method, I actually recommend using this extension method as I find it very useful whenever I have a single object but need an IEnumerable<T> that simply returns that single object.

    Extension method:

    public static class EnumerableYieldExtension
    {
        public static IEnumerable<T> Yield<T>(this T item)
        {
            if (item == null)
                yield break;
    
            yield return item;
        }
    }
    

    The extension method is useful in many scenarios. In your case, you can now do this:

    string[] someArray = new string[] {"test1", "test2", "test3"};
    foo(someArray.Concat("test4".Yield()).ToArray());
    
    0 讨论(0)
提交回复
热议问题