WPF命令行参数,一个聪明的办法? [英] WPF Command Line Arguments, a smart way?

查看:139
本文介绍了WPF命令行参数,一个聪明的办法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找我可以解析的命令行参数到我的WPF应用程序,只需读取用户传入的参数值生活方式。

I'm looking for a way that I can parse command line arguments into my WPF application with just a way of reading the value of the argument that the user passed.

例如

application.exe /setTime 5

有没有办法,我有一些code,我只能说:

is there a way for me to have some code where I can just say:

MessageBox.Show(arg("setTime"));

将输出 5

工作方案

如何创建智能WPF命令行参数

推荐答案

在解析命令行把参数/值对在词典用参数为键。那么你的 ARG(SETTIME)将变为:

When you parse the command line put the argument/value pairs in a Dictionary with the argument as the key. Then your arg("SetTime") will become:

MessageBox.Show(dictionary["SetTime"]);

(显然,你不想让实际的词典是公开的。)

(Obviously you don't want the actual dictionary to be public.)

要获得论点可以使用第一名:

To get the arguments in the first place you can use:

string[] args = Environment.GetCommandLineArgs();

这将返回所有的参数,所以你需要解析2步阵(首先检查其长度是两个+ 1的倍数后):

This will return all the arguments so you will need to parse the array in steps of two (after first checking that the length is a multiple of two + 1):

数组的第一个元素是执行程序的名称 - MSDN页面 - 让你的循环需要从一开始:

The first element of the array is the name of the executing program - MSDN Page - so your loop needs to start from one:

for (int index = 1; index < args.Length; index += 2)
{
     dictionary.Add(args[index], args[index+1]);
}

这个循环在两个步骤,你定义每个参数都是一对值:标识符和本身的实际价值,例如

This loops in steps of two as you define each argument is a pair of values: the identifier and the actual value itself, e.g.

my.exe -arg1 value1 -arg2 value2

然后,你可以简单地看,如果被看到指定的参数,如果该键 -arg1 在字典中,然后读取它的值:

Then you can simply see if the argument is specified by seeing if the key -arg1 is in the dictionary and then read it's value:

string value;
if (dictionary.TryGetValue(arg, out value))
{
    // Do what ever with the value
}

这意味着,你可以在任何顺序的参数和省略不想指定任何参数。

This means you can have the arguments in any order and omit any arguments you don't want to specify.

这篇关于WPF命令行参数,一个聪明的办法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆