控制台应用程序应等待参数

我有一个类似于此的控制台应用程序:


static void Main(string[] args)

{

   if(args.Length == 0)

   {

      //do something

   }

   else if(args.Length % 2 == 0)

   {

      //do something else

   }

}

现在,当我构建并启动我的 .exe 文件时,它只是眨眼间打开以运行代码并关闭。


有没有可能这个.exe启动后在等我输入参数?


我知道我可以打开 cmd 并将目录写入我的文件并写入我的参数 (C:\Example\MyExe.exe -Parameter1)。但这是唯一的方法吗?


慕尼黑8549860
浏览 94回答 4
4回答

海绵宝宝撒

有没有可能这个.exe启动后在等我输入参数?它不会等待,args因为这些应该在您启动应用程序时传入,但您可以使用Console.ReadLine. 这是一个例子:static void Main(string[] args){&nbsp; &nbsp; if (args.Length == 0)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; List<string> arguments = new List<string>();&nbsp; &nbsp; &nbsp; &nbsp; do&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine("Input argument and press <ENTER>: ");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; string argument = Console.ReadLine();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (string.IsNullOrEmpty(argument))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arguments.Add(argument);&nbsp; &nbsp; &nbsp; &nbsp; } while (true);&nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine("continue...");&nbsp; &nbsp; }&nbsp; &nbsp; else if (args.Length % 2 == 0)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; //do something else&nbsp; &nbsp; }}

慕哥9229398

如果您的应用程序打开并立即关闭,那是因为没有“阻塞”方法。您可以Console.Read();在末尾添加一个,等待按下某个键。例如:static void Main(string[] args){&nbsp; &nbsp;if(args.Length == 0)&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; //do something&nbsp; &nbsp;}&nbsp; &nbsp;else if(args.Length % 2 == 0)&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; //do something else&nbsp; &nbsp;}&nbsp; &nbsp;Console.WriteLine("Press any key to exit the application.");&nbsp; &nbsp;Console.Read();}为了传递参数,我习惯于使用cmd并直接将参数传递给exe,但这可以在VS中完成右键单击项目 -> 属性 -> 调试 -> 命令行参数

三国纷争

右键单击默认项目选择“属性”单击左侧的“调试”选项卡。在“命令行参数”中键入命令行参数。保存更新的属性并运行项目。

开心每一天1111

是的,这是唯一的方法,因为参数是在启动应用程序时传递的。如果要调试它,可以在 Visual Studio 中添加调试参数。为此,右键单击项目并打开项目的设置。然后您可以将它们添加到调试部分。查看使用 Visual Studio C# 传递命令行参数以&nbsp;获取更多信息。更多信息:如果您想让您的应用程序保持打开状态,直到用户按下您可以使用的键Console.Read();。
打开App,查看更多内容
随时随地看视频慕课网APP