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