如何以Dictionary <string,string>的形式从控制台应用程序中获取命名参数?

pen*_*ake 19 .net c# string parsing console-application

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

什么是收集传递给这个控制台应用程序了命名参数的最简单方法,然后把它们放在一个Dictionarty<string, string>()里面会有参数名称作为键和值作为参数?

例如:

MyTool foo=123432 bar=Alora barFoo=45.9
Run Code Online (Sandbox Code Playgroud)

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

MyArguments["foo"]=123432 
MyArguments["bar"]="Alora"
MyArguments["barFoo"]="45.9"
Run Code Online (Sandbox Code Playgroud)

Mrc*_*ief 24

使用此Nuget包

需要几秒钟来配置并为您的应用程序添加即时专业触摸.

// 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);
  }
}
Run Code Online (Sandbox Code Playgroud)


Kay*_*Zed 6

以下是如何以最简单的方式完成此操作:

    static void Main(string[] args)
    {
        var arguments = new Dictionary<string, string>();

        foreach (string argument in args)
        {
            string[] splitted = argument.Split('=');

            if (splitted.Length == 2)
            {
                arguments[splitted[0]] = splitted[1];
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

注意:

  • 参数名称区分大小写
  • 多次提供相同的参数名称不会产生错误
  • 不允许有空格
  • 必须使用一个=符号