c# - WPF 命令行参数路由

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

我有一个正在开始开发的 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");

        }
    }
}
}

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

/Task ThisIsTheTask

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

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

最佳答案

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

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<string[]>对于在命令行上指定的任务,并将其余参数传递给 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);

关于c# - WPF 命令行参数路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20059174/

相关文章:

c# - 如何使用 Firebase 管理 SDK 发送消息

c# - 无法访问 asp.net 中对应的 .cs 文件

wpf - 如何在 TextBox 上设置正则表达式?

java - 将颜色设置为 int 值以用于 setRGB(int x, int y, int rgb) 方法? -- java

c# - 如何使用 c# winform 从 datagridview 中编辑的单元格获取数据?

c# - ASP.NET 从母版页调用 Controller 方法?

c# - 确定应用程序从哪个位置启动

c# - 文本 block 行高

javascript - 在 react 中调用作为 Prop 传递的方法

python - 无法访问父类中定义的方法