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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11429970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 17:50:41  来源:igfitidea点击:

How can I obtain the named arguments from a console application in the form of a Dictionary<string,string>?

c#.netstringparsingconsole-application

提问by pencilCake

I have a console application called MyTool.exe

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

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?

收集传递给此控制台应用程序的命名参数,然后将它们放入一个Dictionarty<string, string>()以参数名称作为键和值作为参数的最简单方法是什么?

for example:

例如:

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"

回答by Kay Zed

Here's how this can be done in the most simple way:

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

    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];
            }
        }
    }

Note that:

注意:

  • Argument names are case sensitive
  • Providing the same argument name more than once does not produce an error
  • No spaces are allowed
  • One = sign must be used
  • 参数名称区分大小写
  • 多次提供相同的参数名称不会产生错误
  • 不允许有空格
  • 一 = 必须使用符号

回答by Stig

I don't see why this code is bad? hova?

我不明白为什么这段代码不好?霍瓦?

        var arguments = new Dictionary<string, string>();
        foreach (var item in Environment.GetCommandLineArgs())
        {
            try
            {
                var parts = item.Split('=');
                arguments.Add(parts[0], parts[1]);
            }
            catch (Exception ex)
            {
                // your error handling here....
            }

回答by Mrchief

Use this Nuget package

使用这个 Nuget 包

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);
  }
}

回答by Robert Mc Menamin

if you have a "=" in your parameter values, a safer option would be:

如果您的参数值中有“=”,则更安全的选择是:

private static Dictionary<string, string> ResolveArguments(string[] args)
{
    if (args == null)
        return null;

    if (args.Length > 1)
    {
        var arguments = new Dictionary<string, string>();
        foreach (string argument in args)
        {
            int idx = argument.IndexOf('=');
            if (idx > 0)
                arguments[argument.Substring(0, idx)] = argument.Substring(idx+1);
        }
        return arguments;
    }

    return null;
}