How exactly is `string[] args` populated in a C# Main method?

让人想犯罪 __ 提交于 2021-02-20 06:13:56

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!