Mr.*_*Boy 0 c# .net-3.5 command-line-arguments command-line-parsing
我见过人们编写自定义类来更轻松地处理各种语言的命令行选项。我想知道.NET(3.5或更低版本)是否内置任何东西,以便您不必自定义解析诸如:
myapp.exe file = text.txt
对于不需要任何复杂功能的快速而肮脏的实用程序,控制台应用程序很多时候采用以下形式的命令行:
program.exe command -option1 optionparameter option2 optionparameter
Run Code Online (Sandbox Code Playgroud)
等等。
在这种情况下,要获取“命令”,只需使用 args[0]
要获得一个选项,请使用以下内容:
var outputFile = GetArgument(args, "-o");
Run Code Online (Sandbox Code Playgroud)
其中GetArgument定义为:
string GetArgument(IEnumerable<string> args, string option)
=> args.SkipWhile(i => i != option).Skip(1).Take(1).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)
小智 5
这是另一种可能的方法。很简单,但过去对我有用。
string[] args = {"/a:b", "/c:", "/d"};
Dictionary<string, string> retval = args.ToDictionary(
k => k.Split(new char[] { ':' }, 2)[0].ToLower(),
v => v.Split(new char[] { ':' }, 2).Count() > 1
? v.Split(new char[] { ':' }, 2)[1]
: null);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9321 次 |
| 最近记录: |