简体   繁体   English

输出所有命令行参数

[英]Output all command line parameters

I am working on a console application, that receives a pretty long list of parameters. 我正在研究一个控制台应用程序,它接收了很长的参数列表。 For debugging purpose I need to print the parameters passed to a an output file. 出于调试目的,我需要打印传递给输出文件的参数。 Right now, I am using the following code to concat command line parameters. 现在,我使用以下代码来连接命令行参数。

static void Main(string[] args)
{
    string Params = string.Empty;
    foreach(string arg in args)
    {
       Params += arg + ",";
    }
}

Is there any better way to accomplish this? 有没有更好的方法来实现这一目标?

What about 关于什么

Params = string.Join(",", args);

Your foreach approach is not very performant. 你的foreach方法foreach不高。 Since a string is immutable , that means for each iteration of the loop, the string will get thrown away for garbage collection, and a new string will be generated. 由于字符串是不可变的 ,这意味着对于循环的每次迭代,字符串将被抛弃以进行垃圾收集,并且将生成新的字符串。 In the string.Join case, only one string will be generated. string.Join情况下,只会生成一个字符串。

Inside the loop, to get around the same performance, you will have to use a StringBuilder , but in this case it's really no reason not to use string.Join since the code will be much more readable. 在循环内部,为了获得相同的性能,你将不得不使用StringBuilder ,但在这种情况下,它真的没有理由不使用string.Join因为代码将更具可读性。

你可以使用String.Join(“,”,args)

你可以使用这段代码

String.Join(", ", Environment.GetCommandLineArgs())

All of the answers here combining the arguments with a single comma will work, but I found that approach lacking somewhat because there's not a clear indicator of "quoted arguments" and those that might contain a comma. 这里将所有参数与单个逗号相结合的所有答案都可以使用,但我发现这种方法缺乏某种程度,因为没有明确的“引用参数”指示和可能包含逗号的指示。

Using the example: Foo.exe an example "is \\"fine\\", too" okay 使用示例: Foo.exe an example "is \\"fine\\", too" okay

The simple join suggestions will yield: an, example, is "fine", too, okay . 简单的连接建议将产生: an, example, is "fine", too, okay Not bad, but not very clear and somewhat misleading. 不错,但不是很清楚,有点误导。

Here's what I threw together that works well enough for me. 这就是我扔在一起对我来说足够好的东西。 I'm sure it could be improved further. 我相信它可以进一步改进。

String.Join(", ", (from a in args select '"' + a.Replace("\"", @"\""") + '"'));

It returns the string: "an", "example", "is \\"fine\\", too", "okay" . 它返回字符串: "an", "example", "is \\"fine\\", too", "okay" I think this does a better job indicating the actual parameters. 我认为这可以更好地指出实际参数。

String params = String.Join(",", args);

You should use: 你应该使用:

string.Join(",", args);

Strictly speaking the Join function creates a StringBuilder with capacity strings.Length * 16 (this 16 is a fixed number). 严格来说,Join函数创建一个带有容量字符串的StringBuilder .Length * 16(这16是一个固定的数字)。 If you have different args maximum size and if performance is crucial to you, use a StringBuilder with a specific capacity. 如果您有不同的args最大大小,并且性能对您至关重要,请使用具有特定容量的StringBuilder。

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

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