如何使用未指定数量的参数构建一个方法C#

apa*_*cay 4 c# parameters

这是我的代码:

    private static string AddURISlash(string remotePath)
    {
        if (remotePath.LastIndexOf("/") != remotePath.Length - 1)
        {
            remotePath += "/";
        }
        return remotePath;
    }
Run Code Online (Sandbox Code Playgroud)

但我需要类似的东西

AddURISlash("http://foo", "bar", "baz/", "qux", "etc/");
Run Code Online (Sandbox Code Playgroud)

如果我没记错的话,string.format就是那样......

String.Format("{0}.{1}.{2}.{3} at {4}", 255, 255, 255, 0, "4 p.m.");
Run Code Online (Sandbox Code Playgroud)

C#中有什么东西允许我这样做吗?

我知道我能做到

private static string AddURISlash(string[] remotePath)
Run Code Online (Sandbox Code Playgroud)

但那不是主意.

如果这是某些框架中的某些内容可以完成而在其他框架中没有请指定以及如何解决它.

提前致谢

Jon*_*eet 6

我想你想要一个参数数组:

private static string CreateUriFromSegments(params string[] segments)
Run Code Online (Sandbox Code Playgroud)

然后你实现它知道它remotePath只是一个数组,但你可以调用它:

string x = CreateUriFromSegments("http://foo.bar", "x", "y/", "z");
Run Code Online (Sandbox Code Playgroud)

(如注释中所述,参数数组只能作为声明中的最后一个参数出现.)


Mso*_*nic 5

您可以使用params,它允许您指定任意数量的参数

private static string AddURISlash(params string[] remotePaths)
{
    foreach (string path in remotePaths)
    {
        //do something with path
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,这params会影响代码的性能,因此请谨慎使用.