如何获取 Visual Studio 用于调试工作的 cmd 参数?

How can I get Visual Studio cmd parameters for debugging working?

目前我正在开发 WPF 应用程序。它应该通过带有单个参数的命令行启动。 我定义了:

public App([Optional] string[] args)
{
    //string[] args = new string[] { "UK356715586" };
    Console.WriteLine("accessed app");
    if (args.Length == 0)
    {                
        Environment.Exit(-1);
    }
    else
    {
        Console.WriteLine("Before PONumber Setting");
        PONumber = args[0].ToString();
    }

    //PONumber = "UK356715586";
}

我为给定参数设置了这个调试设置:

通过在 VS 中启动,我得到:

instance of an object."

"args" war "null".

我能做什么?

不要创建参数声明为 [Optional] 的构造函数。它永远不会被分配。如果删除该属性,甚至会出现编译错误。

而是使用 Application 类型的内置 Startup 事件。来自 documentation:

A typical Windows Presentation Foundation application may perform a variety of initialization tasks when it starts up, including:

  • Processing command-line parameters.

[...] application-scope properties and command-line parameters can only be used programmatically. Programmatic initialization can be performed by handling the Startup event [...]

App.xaml中分配一个事件处理程序并在App.xaml.cs中实现它。

<Application x:Class="YourWpfApp.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
             StartupUri="MainWindow.xaml"
             Startup="App_OnStartup">
   <Application.Resources>
      <!-- ...your resources. -->
   </Application.Resources>
</Application>
public partial class App : Application
{
   private void App_OnStartup(object sender, StartupEventArgs e)
   {
      Console.WriteLine("accessed app");
      if (e.Args.Length == 0)
      {                
          Shutdown(-1);
      }
      else
      {
          Console.WriteLine("Before PONumber Setting");
          PONumber = e.Args[0];
      }
   }

   // ...other code.
}

另一种方法是覆盖 App 类型中的 OnStartup 方法。来自 documentation:

OnStartup raises the Startup event.

A type that derives from Application may override OnStartup. The overridden method must call OnStartup in the base class if the Startup event needs to be raised.

public partial class App : Application
{
   protected override void OnStartup(StartupEventArgs e)
   {
      base.OnStartup(e);

      Console.WriteLine("accessed app");
      if (e.Args.Length == 0)
      {                
          Shutdown(-1);
      }
      else
      {
          Console.WriteLine("Before PONumber Setting");
          PONumber = e.Args[0];
      }
   }

   // ...other code.
}