如何显示命令行自变量(C# 编程指南)How to display command line arguments (C# Programming Guide)

可通过 Main 的可选参数来访问在命令行处提供给可执行文件的参数。Arguments provided to an executable on the command-line are accessible through an optional parameter to Main. 参数以字符串数组的形式提供。The arguments are provided in the form of an array of strings. 数组的每个元素都包含 1 个参数。Each element of the array contains one argument. 删除参数之间的空格。White-space between arguments is removed. 例如,下面是对虚构可执行文件的命令行调用:For example, consider these command-line invocations of a fictitious executable:

命令行输入Input on Command-line 传递给 Main 的字符串数组Array of strings passed to Main
executable.exe a b cexecutable.exe a b c "a""a"

"b""b"

“c”"c"
executable.exe one twoexecutable.exe one two "one""one"

"two""two"
executable.exe "one two" threeexecutable.exe "one two" three "one two""one two"

"three""three"

备注

在 Visual Studio 中运行应用程序时,可在“项目设计器”->“调试”页中指定命令行参数。When you are running an application in Visual Studio, you can specify command-line arguments in the Debug Page, Project Designer.

示例Example

本示例显示了传递给命令行应用程序的命令行参数。This example displays the command line arguments passed to a command-line application. 显示的输出对应于上表中的第一项。The output shown is for the first entry in the table above.

class CommandLine
{ 
    static void Main(string[] args)
    {
        // The Length property provides the number of array elements.
        Console.WriteLine($"parameter count = {args.Length}");

        for (int i = 0; i < args.Length; i++)
        {
            Console.WriteLine($"Arg[{i}] = [{args[i]}]");
        }
    }
}
/* Output (assumes 3 cmd line args): 
    parameter count = 3
    Arg[0] = [a]
    Arg[1] = [b]
    Arg[2] = [c]
*/

请参阅See also