• BiaoDoo首页
  • 自主产品
       自主产品
       测试工具
       源码安全/质量测试云平台
       测试用例开发工具
       软件测试态势分析平台
       开源软件安全审计系统
       软件造价
       软件造价概算平台
       运维产品
       应用源码监测系统
       教学实训平台
       软件测试实验室平台
  • Micro Focus产品代理
       Micro Focus产品代理
       Fortify SCA
       Webinspect
       LoadRunner
       ALM/QualityCenter
       MF UFT
       MF Mobile Center
       Diagnostics
  • 其它产品
       其它产品
       AppScan(IBM)
       Klockwork Insight
       Coverity静态分析
       Black Duck--黑鸭软件成分分析
  • 安全产品
       安全产品
       U盾
  • 工程咨询
       工程咨询
       IT规划咨询
       软件造价概算
       软件架构评估
       信息工程监理
       测试体系咨询
  • 软件测试
       软件测试
       工程验收测试
       压力测试与优化
       产品认证测试
       专题测试
       医疗设备软件测试
       摇号软件测试
       科研项目验收
       软件故障诊断
       委托客制测试
       软件登记测试
       科技成果鉴定
       国产软件适配测试
  • 安全测试
       安全测试
       软件安全测试
       源码安全测试
       等级保护测评
       渗透测试
       风险评估
  • 企业服务
       企业服务
       系统保障与救援
       大数据服务
       ICP证书办理
       软件著作权
       首版次申报
  • 教育培训
       教育培训
       ISTQB认证
       软件产品检验员
       软件就业培训
       校企合作
       信息安全培训
  • 认证中心
       认证中心
       软件企业认证
       质量安全体系认证
       高新技术企业认证
       企业能力认证
       节能与绿色评价服务
       其它系统认证
  • 资讯中心
       资讯中心
       最新资讯
       政策法规
       技术方案
  • 开源测试 · 青云渡
       开源测试 · 青云渡
       技术文摘
       BiaoDoo开源
       常用工具
  • 全国网络
       全国网络
  • BiaoDoo
       BiaoDoo
       软件管控领导者
       合作伙伴
       FAQ
       加入我们
       招聘信息
       合作加盟
       联系我们
  • 测试外包
       测试外包
       离岸测试外包
       测试人才外协
  • 开源测试 · 青云渡

    NDesk.Options使用详解(Mono.Options)

            NDesk.Options是用于C#命令行参数解析的开源库,又名Mono.Options。支持解析布尔参数(Boolean Options)、值参数(Value Options)、捆绑参数(Bundled parameters)。在进行参数解析的时候,允许自定义回调函数。

    • 官方网页地址为http://www.ndesk.org/Options

    • Github上地址为https://github.com/mono/mono/tree/master/mcs/class/Mono.Options/


        应用示例:

    using NDesk.Options;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
     
    namespace NDeskOptionDemo
    {
        class Program
        {
            static int verbosity;
     
            public static void Main(string[] args)
            {
                bool show_help = false;
                List<string> names = new List<string>();
                int repeat = 1;
     
                // 第一阶段:初始化
                var p = new OptionSet() {
                // 注册 解析必填参数(required)、参数描述、解析回调函数
                { "n|name=", "the {NAME} of someone to greet.",
                  v => names.Add (v) },
                // 注册解析必填参数(required)、参数描述、解析回调函数
                { "r|repeat=",
                    "the number of {TIMES} to repeat the greeting.\n" +
                        "this must be an integer.",
                  (int v) => repeat = v },
                // 注册解析布尔参数(boolean)、参数描述、解析回调函数
                { "v", "increase debug message verbosity",
                  v => { if (v != null) ++verbosity; } },
                // 注册解析布尔参数(boolean)、参数描述、解析回调函数
                { "h|help",  "show this message and exit",
                  v => show_help = v != null },
            };
     
                List<string> extra;
                try
                {
                    // 第二阶段:解析,未解析的参数将放置到变量extra中
                    extra = p.Parse(args);
                }
                catch (OptionException e)
                {
                    Console.Write("greet: ");
                    Console.WriteLine(e.Message);
                    Console.WriteLine("Try `greet --help' for more information.");
                    return;
                }
     
                if (show_help)
                {
                    ShowHelp(p);
                    return;
                }
     
                string message;
                if (extra.Count > 0)
                {
                    message = string.Join(" ", extra.ToArray());
                    Debug("Using new message: {0}", message);
                }
                else
                {
                    message = "Hello {0}!";
                    Debug("Using default message: {0}", message);
                }
     
                foreach (string name in names)
                {
                    for (int i = 0; i < repeat; ++i)
                    {
                        //Console.WriteLine("-------------in loop--------------");
                        //Console.WriteLine("message = {0}", message);
                        //Console.WriteLine("name[{0}] = {1}", i, name);
                        Console.WriteLine(message, name);
                        
                    } 
                }
     
                Console.ReadKey();
            }
     
            static void ShowHelp(OptionSet p)
            {
                Console.WriteLine("Usage: greet [OPTIONS]+ message");
                Console.WriteLine("Greet a list of individuals with an optional message.");
                Console.WriteLine("If no message is specified, a generic greeting is used.");
                Console.WriteLine();
                Console.WriteLine("Options:");
                p.WriteOptionDescriptions(Console.Out);
            }
     
            static void Debug(string format, params object[] args)
            {
                if (verbosity > 0)
                {
                    Console.Write("# ");
                    Console.WriteLine(format, args);
                }
            }
        }
    }

    使用介绍

    参数解析分为两个阶段:初始化和解析。分别对应上面代码var p = new OptionSet() {...} 和p.Parse(args);


    NDesk.Options会把“-”、“--”、“/”认为是参数名(OptionName)进行解析并赋予参数值(OptionValue),举例说明


    a.exe -n 10 --name=9  /opt:true ?123


    经解析后,参数名n的参数值为10,name的值为9,opt的值为true。而?123是未被处理的多余字符串。在未定义默认解析函数情况下,经解析后多余字符串会通过parse()函数返回,例如下面的extra就存放了多余字符串:

    public static void Main(string[] args)
    {
        ...
     
        List<string> extra = p.Parse(args);
     
        ...
    }

    关于默认解析函数请参考下一节内容


    初始化

    初始化的目的对于使用者来说就是注册要解析的参数名、参数名的描述以及匹配到参数名后的回调函数。例如

    var p = new OptionSet() {{ "n|name=", "the {NAME} of someone to greet.",  v => names.Add (v) }}

    "n|name=" 表示参数名原型(Prototype),此处表示该参数名可以缩写为-n或者全称-name(注意先要声明参数名缩写,再声明参数名全称)

    "the {NAME} of someone to greet."作用时在调用p.WriteOptionDescriptions(Console.Out)后,将打印出该参数名的描述

    v => names.Add (v)表示在解析到参数名n时将参数值添加到names中(lamda表达式)

    如果想为这些未匹配的参数名提供默认解析函数,可以这样注册,注意“<>”这个参数名即为默认解析函数

    var p = new OptionSet() {
    { "n|name=", "the {NAME} of someone to greet.",  v => names.Add (v) },
    { "<>", v => Console.WriteLine ("default handler: {0}", v)}
    }

    参数名有三种类型:布尔型(Boolean)、必输型(Required)、选输型(Optional),用无符号、等号、冒号来区别


    var p = new OptionSet() {

    //布尔,例如采用-opt+、--opt-、/opt均可以为赋值

    { "o|opt", "the {opt} of someone to greet.",  v => flag = (v == null) },

    //必输

    { "n2|name2=", "the {NAME2} of someone to greet.",  v => names.Add (v) },

    //选输

    { "n3|name3", "the {NAME3} of someone to greet.",  v => names.Add (v) },

    }

    解析

    通例子来说明参数解析,以加深对NDesk.Options的理解。仍然考虑代码示例章节的代码

    ##show_help为真,执行ShowHelp(p);打印参数名描述
    greet.exe --help
    Usage: greet [OPTIONS]+ message
    Greet a list of individuals with an optional message.
    If no message is specified, a generic greeting is used.
     
    Options:
      -n, --name=NAME            the NAME of someone to greet.
      -r, --repeat=TIMES         the number of TIMES to repeat the greeting.
                                   this must be an integer.
      -v                         increase debug message verbosity
      -h, --help                 show this message and exit
     
    ##v为false,不打印调试信息
    ##names包含A、B、C、D、E参数值
    ##extra为空,表示无未处理的字符串,则按照hello XXX!进行打印
    ##repeat未解析到,采用默认值1,即重复打印1次
    greet.exe -v- -n A -name=B --name=C /name D -nE
    Hello A!
    Hello B!
    Hello C!
    Hello D!
    Hello E!
     
    ##v为true,打印调试信息
    ##names包含E参数值
    ##extra为 custom greeting for: {0},则按照custom greeting for: XXX进行打印
    greet.exe -v -n E custom greeting for: {0}
    # Using new message: custom greeting for: {0}
    custom greeting for: E
     
    ##names包含A参数值
    ##extra为空,表示无未处理的字符串,则按照hello XXX!进行打印
    ##repeat为3,重复打印3次
    greet.exe -r 3 -n A
    Hello A!
    Hello A!
    Hello A!
     
    ##repeat只能接受int类型,不能将not-an-int转换成int,抛出异常
    ##源代码中关于reapeat类型检查,代码为(int v) => repeat = v
    greet.exe -r not-an-int
    greet: Could not convert string `not-an-int' to type Int32 for option `-r'.
    Try `greet --help' for more information.


    其他同类组件:

    BiaoDoo·智慧测试 | 让软件更可靠

    本站声明:内容源自https://blog.csdn.net/tangtao_xp/article/details/85958637(NDesk.Options使用详解(Mono.Options))