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

我的梦境 提交于 2020-03-16 03:52:14

问题


Example:

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

We can call this method with:

a) foo("test", "test2", "test3") // multiple single strings
b) foo(new string[]{"test", "test2", "test3"}) // string array

But it is not possible to call the method with:

c) foo("test", new string[]{"test", "test2", "test3"})

So when I have a single string and an array of strings, do I have to put them into one array first to call the method? Or is there a nice workaround to tell the method to consider the string array as single strings?


回答1:


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());



回答2:


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)
{
} 



回答3:


Just add your string to the array:

var newArray = new string[oldArray.length+1];
newArray[0]=yourString;
oldArray.CopyTo(newArray, 1);

foo(newArray);



回答4:


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.



来源:https://stackoverflow.com/questions/18017209/how-to-pass-an-array-and-a-single-element-to-a-multiple-argument-method

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