【问题标题】:WPF Command Line Argument RoutingWPF 命令行参数路由
【发布时间】:2013-12-02 06:36:35
【问题描述】:

我有一个正在开始开发的 WPF 应用程序。我有大约 40 种方法可以通过 UI 访问,但也需要通过命令行传递参数来执行。

目前我有以下内容,这使我可以捕获 App.xaml.cs 上的参数...

    public partial class App : Application
    {
    string[] args = MyApplication.GetCommandLineArgs();

    Dictionary<string, string> dictionary = new Dictionary<string, string>();

    private void Application_Startup(object sender, StartupEventArgs e)
    {
        for (int index = 1; index < args.Length; index += 2)
        {
            dictionary.Add(args[index], args[index + 1]);
        }

        if (dictionary.Keys.Contains("/Task"))
        {
            MessageBox.Show("There is a Task");

        }
    }
}
}

我希望在每次调用开始时通过命令行传递一个参数。如果我通过了

/任务这就是任务

我可以从字典里读到这个。然后执行相关方法。

我的问题是将任务参数“路由”到特定方法的最佳方式是什么。我还将在需要传递给方法的任务之后传递其他参数。

【问题讨论】:

    标签: c# wpf methods parameters command-line-arguments


    【解决方案1】:

    它可以被认为是服务定位器反模式的一种实现,但一种简单的方法是使用如下内容:

    private readonly Dictionary<string, Action<string[]>> commands = new Dictionary<string, Action[]>
    {
        {"Task1", args => Task1Method(args[0], Int32.Parse(args[1]))}
    }
    
    private static Task1Method(string firstArgs, int secondArg)
    {
    }
    

    然后,您的代码可以为命令行中指定的任务找到Action&lt;string[]&gt;,并将其余参数传递给Action,例如

    var commandLineArgs = Environment.GetCommandLineArgs();
    var taskName = commandLineArgs[1];
    
    // Locate the action to execute for the task
    Action<string[]> action;
    if(!commands.TryGetValue(taskName, out action))
    {
        throw new NotSupportedException("Task not found");
    }
    
    // Pass only the remaining arguments
    var actionArgs = new string[commandLineArgs.Length-2];
    commandLineArgs.CopyTo(actionArgs, 2);
    
    // Actually invoke the handler
    action(actionArgs);
    

    【讨论】:

      【解决方案2】:

      如果您能够使用第三方开源库,我建议您查看ManyConsole,它可以通过 NuGet here 获得。

      ManyConsole 允许您定义ConsoleCommand 实现(参见here 示例实现),它可以有许多参数。然后,您可以根据命令行参数使用ConsoleCommandDispatcher 路由到适当的ConsoleCommand 实现(参见here 示例)。

      我与 ManyConsole 没有任何关系,但我使用过这个库,发现它非常有效。

      【讨论】:

      • 看起来不错@Lukazoid,不幸的是我不能使用任何第三方库。不过谢谢。我会为将来添加书签:-)
      • @MrBeanzy 啊,真可惜,希望你能从这个项目中得到一些启发,我会把这个答案留在这里,以防其他人发现这些信息有用。
      【解决方案3】:

      我建议在您的程序的应用程序类上使用一个(或多个)属性来公开它们。然后可以使用类似的东西在运行时访问

      (Application.Current as App).MyTask
      

      为了方便,可以进一步包装。 此外,您也可以在 WPF 中编写自己的“Main”方法 - 这样您就可以更轻松地访问参数数组,并且如果需要,可以在 WPF 启动之前进行处理。如果您需要,我会修改。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-05-11
        • 2010-09-26
        • 2010-09-14
        • 2020-11-26
        • 2012-03-10
        • 2011-05-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多