如何从控制台应用程序以Dictionary< string,string>的形式获取命名参数? [英] How can I obtain the named arguments from a console application in the form of a Dictionary<string,string>?

查看:70
本文介绍了如何从控制台应用程序以Dictionary< string,string>的形式获取命名参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为MyTool.exe的控制台应用程序

I have a console application called MyTool.exe

最简单的方法是收集传递给此控制台应用程序的命名参数,然后将其放入Dictionarty<string, string>()中,该参数将以参数名称作为键,并以值作为参数?

What is the simplest way to collect the named arguments passed to this console applicaiton and then to put them in a Dictionarty<string, string>() which will have the argument name as the key and the value as the argument?

例如:

MyTool foo=123432 bar=Alora barFoo=45.9

我应该能够获得一个字典:

I should be able to obtain a dictionary which will be:

MyArguments["foo"]=123432 
MyArguments["bar"]="Alora"
MyArguments["barFoo"]="45.9"

推荐答案

使用此Nuget程序包

Use this Nuget package

  • V1.9.x - Command Line Parser Library (CodePlex - Going away soon and out of date)
  • V2+ - Command Line Parser (Ongoing support)

只需几秒钟即可进行配置,并为您的应用程序增加即时的专业触感.

Takes seconds to configure and adds instant professional touch to your application.

// Define a class to receive parsed values
class Options {
  [Option('r', "read", Required = true,
    HelpText = "Input file to be processed.")]
  public string InputFile { get; set; }

  [Option('v', "verbose", DefaultValue = true,
    HelpText = "Prints all messages to standard output.")]
  public bool Verbose { get; set; }

  [ParserState]
  public IParserState LastParserState { get; set; }

  [HelpOption]
  public string GetUsage() {
    return HelpText.AutoBuild(this,
      (HelpText current) => HelpText.DefaultParsingErrorsHandler(this, current));
  }
}

// Consume them
static void Main(string[] args) {
  var options = new Options();
  if (CommandLine.Parser.Default.ParseArguments(args, options)) {
    // Values are available here
    if (options.Verbose) Console.WriteLine("Filename: {0}", options.InputFile);
  }
}

这篇关于如何从控制台应用程序以Dictionary&lt; string,string&gt;的形式获取命名参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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