如何将数组和单个元素传递给多参数方法? [英] How to pass an array and a single element to a multiple argument method?

查看:92
本文介绍了如何将数组和单个元素传递给多参数方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

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?

推荐答案

虽然无需使用扩展方法即可解决此问题,但我实际上建议使用此扩展方法,因为只要有一个对象但需要一个对象,它就会非常有用IEnumerable< T >,仅返回该单个对象.

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.

扩展方法:

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

这篇关于如何将数组和单个元素传递给多参数方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆