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 fil开发者_C百科e. 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. 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.
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.
You could use this piece of code
String.Join(", ", Environment.GetCommandLineArgs())
You can use String.Join(",",args)
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
The simple join suggestions will yield: 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"
. 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). If you have different args maximum size and if performance is crucial to you, use a StringBuilder with a specific capacity.
精彩评论