问题
How exactly is string[] args
populated in a C# Main method?
For instance, is white space stripped? Are any of the elements ever empty string or null? How are single and double quotes handled?
MSDN doesn't explain how and merely says
The parameter of the Main method is a String array that represents the command-line arguments
回答1:
When you start a process, you can pass a string as your argument. How those are arranged and split up is entirely up to you.
So if using the Windows command line, you ran:
myexe.exe "Hello World" Joe Bloggs
Your array would contain:
{"Hello World", "Joe", "Bloggs"}
But it's only split up in that particular way (notice the quotes around Hello World are removed) because the .Net framework is automatically parsing it for you.
回答2:
I believe the args given to Main are those returned by Environment.GetCommandLineArgs() after removing the first of the list. MSDN describes the suprisingly complex logic concerning backslashes:
Command line arguments are delimited by spaces. You can use double quotation marks (") to include spaces within an argument. The single quotation mark ('), however, does not provide this functionality.
If a double quotation mark follows two or an even number of backslashes, each proceeding backslash pair is replaced with one backslash and the double quotation mark is removed. If a double quotation mark follows an odd number of backslashes, including just one, each preceding pair is replaced with one backslash and the remaining backslash is removed; however, in this case the double quotation mark is not removed.
Thanks to Christian.K in the comments.
回答3:
The parameters passed to your program are operating-system dependent.
You should test arguments for nulls, empty strings, strip white-space, and handle single/double quotes within your program (as necessary).
来源:https://stackoverflow.com/questions/12527843/how-exactly-is-string-args-populated-in-a-c-sharp-main-method