键值对作为控制台应用程序中的参数

Vac*_*ano 6 c# parameters command-line console-application

是否有一种简单的方法允许将键/值对(两个字符串)集合作为控制台应用程序的命令行参数?

Dan*_*iel 9

如果你的意思是命令行看起来像这样:c:> YourProgram.exe/switch1:value1/switch2:value2 ...

这可以在启动时轻松解析,看起来像这样:

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

然后,您可以在cmdArgs字典中进行查找.不确定这是不是你想要的.


Bal*_*a R 6

没有从命令行精确传递键/值对的好方法。唯一可用的是一个字符串数组,您可以遍历该字符串并将其提取为键/值对。

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

   }
}
Run Code Online (Sandbox Code Playgroud)

然后打电话

Class1.exe密钥1值1密钥2值2