首页 > 解决方案 > 命令行解析器 NUGet 包让简单的示例程序工作

问题描述

我发现这非常具有挑战性,我感谢您愿意为我提供的任何帮助。

目前我正在尝试实现命令行解析器(https://github.com/commandlineparser/commandline)。

我只想让一个基本的示例应用程序正常工作,但我被卡住了。

最终我想要以下模式

MyProgram -soureid 1231 -domain alpha

我将 sourceid 和 domain 作为有效变量。sourceid 的值为 1231,domain 的值为“alpha”。

这是一个 C# .net 核心应用程序 (2.3),我正在运行 Visual Studio 2017。

这是我到目前为止的代码...

    using System;
using CommandLine;

namespace Program
{
    class Program
    {
        public static void Main(String[] args)
        {
            var options = new SomeOptions();

            CommandLine.Parser.Default.ParseArguments(args, typeof(SomeOptions));

            Console.WriteLine(options.Age);

            Console.ReadLine();
        }
    }
    class SomeOptions
    {
        [Option('n', "name", Required = true)]
        public string Name { get; set; }

        [Option('a', "age")]
        public int Age { get; set; }
    }
}

此代码不起作用。当我通过 -n Jason 我得到这个..

CommandLineArgumentParsing 1.0.0
Copyright (C) 2019 CommandLineArgumentParsing

ERROR(S):
  Verb '-n' is not recognized.

  --help       Display this help screen.

  --version    Display version information.

0

我相信这个问题与这条线有关..

 CommandLine.Parser.Default.ParseArguments(args, typeof(SomeOptions));

这条线似乎应该是这样的..

 CommandLine.Parser.Default.ParseArguments(args, typeof(options));

但是编译器抱怨“'options'是一个变量,但用作类型”

我究竟做错了什么?

标签: c#.net-corevisual-studio-2017

解决方案


在我问这个问题后大约两秒钟,我想通了..

代替..

CommandLine.Parser.Default.ParseArguments(args, typeof(SomeOptions));

和...

Parser.Default.ParseArguments<SomeOptions>(args).WithParsed(parsed => options = parsed);

推荐阅读