c# - 无法理解命令行参数。

标签 c# visual-studio-2015 command-line-arguments

我最近开始学习 C#,并在阅读有关 filesystemwatcher 类的内容时,对命令行参数感到困惑。

从这里:https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2

我复制了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/

相关文章:

c# - 如何将 CF_DIBV5 从剪贴板 (Format17) 转换为透明位图?

c# - 如何从 Access .mdb 文件创建 .edmx 模型?

c# - 是否可以在一个赋值语句中将多个方法链接到一个委托(delegate)?

c++ - Visual Studio 2015 中的警告 C4594

c# - 用于 Unity3D 的 Visual Studio 2015 错误 "Incompatible Project"

c# - 如何使用 C# 在 python 中将字符串作为命令行参数传递

string - 如何将带有多个参数的单个字符串传递给std::process::Command?

c# - 返回值样式问题

Java 1.5 ExitO OutOfMemory?

android - 在 Android 上使用 Visual Studio 2015 调试停止工作