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

这是我的代码:

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 pm"); 

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

我知道我能做到

 private static string AddURISlash(string[] remotePath) 

但那不是主意。

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

提前致谢

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

 private static string AddURISlash(params string[] remotePaths) { foreach (string path in remotePaths) { //do something with path } } 

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

我想你想要一个参数数组

 private static string CreateUriFromSegments(params string[] segments) 

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

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

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

尝试

 private static string AddURISlash(params string[] remotePath) 

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

这可能是你正在寻找的(注意params关键字):

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