简体   繁体   English

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

[英]How to build a method with unspecified amount of params en C#

This is my code: 这是我的代码:

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

But I need something like 但我需要类似的东西

AddURISlash("http://foo", "bar", "baz/", "qux", "etc/");

If I recall correctly, string.format is somehow like that... 如果我没记错的话,string.format就是那样......

String.Format("{0}.{1}.{2}.{3} at {4}", 255, 255, 255, 0, "4 p.m.");

Is there something in C# that allows me to do so? C#中有什么东西允许我这样做吗?

I know I could do 我知道我能做到

private static string AddURISlash(string[] remotePath)

but that's not the idea. 但那不是主意。

If this is something in some framework can be done and in others not please specify and how to resolve it. 如果这是某些框架中的某些内容可以完成而在其他框架中没有请指定以及如何解决它。

Thanks in advance 提前致谢

I think you want a parameter array : 我想你想要一个参数数组

private static string CreateUriFromSegments(params string[] segments)

Then you implement it knowing that remotePath is just an array, but you can call it with: 然后你实现它知道remotePath只是一个数组,但你可以调用它:

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

(As noted in comments, a parameter array can only appear as the last parameter in a declaration.) (如注释中所述,参数数组只能作为声明中的最后一个参数出现。)

You can use params, which lets you specify any amount of arguments 您可以使用params,它允许您指定任意数量的参数

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

Note that params will impact the performance of your code, so use it sparingly. 请注意, params会影响代码的性能,因此请谨慎使用它。

Try 尝试

private static string AddURISlash(params string[] remotePath)

That will allow you to pass a string[] as a number of separate parameters. 这将允许您将string[]作为许多单独的参数传递。

This might be what you're looking for (note the params keyword): 这可能是您正在寻找的(请注意params关键字):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM