如何在C#中构建一个具有未指定参数数量的方法

4
这是我的代码:

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

但我需要类似这样的东西
AddURISlash("http://foo", "bar", "baz/", "qux", "etc/");

如果我没记错的话,string.format应该是这样的...
String.Format("{0}.{1}.{2}.{3} at {4}", 255, 255, 255, 0, "4 p.m.");

有没有C#中的某些功能可以帮助我做到这一点?

我知道我可以这样做

private static string AddURISlash(string[] remotePath)

但这不是我们的初衷。

如果在某些框架中可以实现,而在其他框架中无法实现,请具体说明并提供解决方法。

谢谢您的帮助。


1
http://msdn.microsoft.com/en-us/library/w5zay9db%28v=vs.100%29.aspx - Tim Schmelter
4个回答

6

我认为你需要一个参数数组

private static string CreateUriFromSegments(params string[] segments)

然后您需要实现它,知道remotePath只是一个数组,但您可以使用以下方式调用它:

string x = CreateUriFromSegments("http://foo.bar", "x", "y/", "z");

(如评论中所述,参数数组只能出现在声明的最后一个参数中。)

还有一点需要提到的是,它必须是方法签名中的最后一个参数。 - ntziolis
@apacay 为什么你在使用1.1版本? - Scott Chamberlain
我已经使用C#有一段时间了,但从未听说过这个功能。谢谢。 - Patrick Lorio
下次我会做好,这是我的错误。如果这是某个框架中可以完成而在其他框架中无法完成的事情,请指明如何解决。由于我处理的是这种多样性,我认为那条信息已经足够了。 - apacay
对不起,那我下次会改进。英语不是我的母语。 - apacay
显示剩余4条评论

5
您可以使用“params”来指定任意数量的参数。
private static string AddURISlash(params string[] remotePaths)
{
    foreach (string path in remotePaths)
    {
        //do something with path
    }
}

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

这会让我同时使用数组和参数的写法吗?还是说我需要进行重载?params关键字在1.1中存在吗? - apacay
你应该可以在1.1中毫无问题地使用params。 :) - Msonic
@Msonic "不是字符串数组" -> 对于这个签名,调用AddURISlash(new string[] { "foo", "bar", "baz" });是有效的。 - Firo

3

尝试

private static string AddURISlash(params string[] remotePath)

这将允许您将 string[] 作为多个独立参数传递。


3

这可能是您正在寻找的内容(请注意params关键字):

private static string AddURISlash(params string[] remotePath) {
    // ...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接