Key value pair as a param in a console app

自闭症网瘾萝莉.ら 提交于 2019-12-10 13:18:17

问题


Is there an easy way to allow a collection of Key/Value pairs (both strings) as command line parameters to a console app?


回答1:


If you mean having a commandline looking like this: c:> YourProgram.exe /switch1:value1 /switch2:value2 ...

This can easily be parsed on startup with something looking like this:

private static void Main(string[] args)
{
   Regex cmdRegEx = new Regex(@"/(?<name>.+?):(?<val>.+)");

   Dictionary<string, string> cmdArgs = new Dictionary<string, string>();
   foreach (string s in args)
   {
      Match m = cmdRegEx.Match(s);
      if (m.Success)
      {
         cmdArgs.Add(m.Groups[1].Value, m.Groups[2].Value);
      }
   }
}

You can then do lookups in cmdArgs dictionary. Not sure if that's what you want though.




回答2:


There is no good way to precisely pass key/value pairs from command-line. The only thing that's available is an array of string which you can loop through and extract as key/value pairs.

using System;

public class Class1
{
   public static void Main(string[] args)
   {
      Dictionary<string, string> values = new Dictionary<string, string>();

      // hopefully you have even number args count.
      for(int i=0; i < args.Length; i+=2){
      {
           values.Add(args[i], args[i+1]);
      }

   }
}

and then call

Class1.exe key1 value1 key2 value2




回答3:


The entry point of an application is a main method that can take a string[] of the arguments (these are the command line arguments).

This can't be changed. See MSDN.

To make working with this easier, there are many command line helper libraries that can be used.

One such library is .NET CLI, from the MONO guys, and many others.



来源:https://stackoverflow.com/questions/5955456/key-value-pair-as-a-param-in-a-console-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!