Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

c# - 在C#中解析命令行参数的最佳方法? [关闭](Best way to parse command line arguments in C#? [closed])

When building console applications that take parameters, you can use the arguments passed to Main(string[] args) .

(构建带有参数的控制台应用程序时,可以使用传递给Main(string[] args) 。)

In the past I've simply indexed/looped that array and done a few regular expressions to extract the values.

(过去,我只是索引/循环该数组,并做了一些正则表达式来提取值。)

However, when the commands get more complicated, the parsing can get pretty ugly.

(但是,当命令变得更复杂时,解析可能会变得很丑陋。)

So I'm interested in:

(所以我对以下内容感兴趣:)

  • Libraries that you use

    (您使用的库)

  • Patterns that you use

    (您使用的模式)

Assume the commands always adhere to common standards such as answered here .

(假定命令始终遵循通用标准,例如此处回答 。)

  ask by Paul Stovell translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I would strongly suggest using NDesk.Options ( Documentation ) and/or Mono.Options (same API, different namespace).

(我强烈建议使用NDesk.Options文档 )和/或Mono.Options (相同的API,不同的名称空间)。)

An example from the documentation :

(文档中示例 :)

bool show_help = false;
List<string> names = new List<string> ();
int repeat = 1;

var p = new OptionSet () {
    { "n|name=", "the {NAME} of someone to greet.",
       v => names.Add (v) },
    { "r|repeat=", 
       "the number of {TIMES} to repeat the greeting.
" + 
          "this must be an integer.",
        (int v) => repeat = v },
    { "v", "increase debug message verbosity",
       v => { if (v != null) ++verbosity; } },
    { "h|help",  "show this message and exit", 
       v => show_help = v != null },
};

List<string> extra;
try {
    extra = p.Parse (args);
}
catch (OptionException e) {
    Console.Write ("greet: ");
    Console.WriteLine (e.Message);
    Console.WriteLine ("Try `greet --help' for more information.");
    return;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...