.NET[C#]读取命令行参数的更好的姿势

.NET 作者: Rector 382阅读 0评论 0收藏 收藏本文

郑重申明:本文未经许可,禁止任何形式转载

关于.NET[C#]读取命令行参数的更好的姿势,在这里给大家推荐一个常用的方法或者类库。

NDesk.Options

NDesk.Options官网地址:http://www.ndesk.org/Options
文档地址:http://www.ndesk.org/doc/ndesk-options/

使用示例:

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.\n" + 
          "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;
}

Command Line类库

Command Line类库的源码托管地址:http://commandline.codeplex.com/
使用示例:

class Options
{
    [Option("i", "input", Required = true, HelpText = "Input file to read.")]
    public string InputFile { get; set; }

    [Option(null, "length", HelpText = "The maximum number of bytes to process.")]
    public int MaximumLenght { get; set; }

    [Option("v", null, HelpText = "Print details during execution.")]
    public bool Verbose { get; set; }

    [HelpOption(HelpText = "Display this help screen.")]
    public string GetUsage()
    {
        var usage = new StringBuilder();
        usage.AppendLine("Quickstart Application 1.0");
        usage.AppendLine("Read user manual for usage instructions...");
        return usage.ToString();
    }
}

阅读了该文章的人还浏览了...

本文永久链接码友网 » .NET[C#]读取命令行参数的更好的姿势

发布于: 2017-12-31 09:32:00
分享扩散:

文章评论

获取验证码