我最近开始学习 C#,并在阅读有关 filesystemwatcher 类的内容时,对命令行参数感到困惑。
我复制了c#,当我阅读代码时我很困惑,因为它说如果参数不等于2基本上就不会继续。我以为只有参数,目录路径?当我打印出 args[0] 和 args[1] 时,它打印了 watcher.exe 和目录,但是我认为该目录是 watcher.exe 的参数,而不是 watcher.exe 本身是参数?当我查看这个示例( https://msdn.microsoft.com/en-gb/library/aa288457(v=vs.71).aspx )时,它没有显示在打印参数时打印的 cmdline2 ,如果有人知道原因,那就太好了。
另外一个问题是,我确实尝试编写 args[2] 行,这当然导致了应用程序崩溃。我以为我会在 VS 2015 中测试调试器,但是当我需要将参数传递给应用程序时,我不知道如何调试我的代码?我看到的只是一个开始按钮,没有参数选项。
最佳答案
发生这种情况的原因是 args[]
参数数组以一种特殊的方式构造,其原因与传统无关。 (我相信这是从 Unix C 中的 main()
函数开始的传统。)每个人都熟悉它,所以每个人都认为它很正常,但如果你是第一次看到这个,你感到困惑是可以理解的。
这是args[]
的格式:
args[0] = the pathname of the executable file from which the current process started.
args[1] = the first argument passed to the program.
args[2] = the second argument passed to the program.
and so on.
因此,args
的长度将始终大于或等于 1,因为总会有一个可执行文件从中当前进程已启动。
那么这当然会变得棘手,因为如果你想确保你的程序传递了 1 个且仅 1 个参数,你必须执行 if( args.Length == 2 )
。这就是你困惑的根源。
不幸的是,人们认为这种事情太“正常”,以至于他们甚至懒得去记录正在发生的巫术。
修改
更糟糕的是,微软正试图用 C# 来“纠正”这种不幸的情况,但他们并不一致:
在“Main() 和命令行参数(C# 编程指南)”( https://msdn.microsoft.com/en-us/library/acy3edy3.aspx ) 中,他们说:
Unlike C and C++, the name of the program is not treated as the first command-line argument.
但是在 System.Environment.GetCommandLineArgs() 的文档中,( https://msdn.microsoft.com/en-us/library/system.environment.getcommandlineargs(v=vs.110).aspx ) 他们说:
The first element is the executable file name, and the following zero or more elements contain the remaining command-line arguments.
(请记住,当我们说“第一个元素”时,我们指的是索引为零的元素。)
因此,索引零处的参数可能是也可能不是可执行文件;这取决于您手中的参数数组是否是传递给 Main()
函数的参数,或者您是否通过调用 System.Environment.GetCommandLineArgs( )
。
不错吗?我知道了,告诉我吧。
关于c# - 无法理解命令行参数。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39757859/