【问题标题】:Command Line Parser library giving 'System.Type' error in C#命令行解析器库在 C# 中给出“System.Type”错误
【发布时间】:2019-11-05 18:17:11
【问题描述】:

我正在用 C# 编写控制台应用程序 (.NET Framework)。我想使用命令行中的参数,并且我正在尝试使用命令行解析器库来帮助我做到这一点。

这是 Nuget 上的包 - https://www.nuget.org/packages/CommandLineParser/

我是从这个 StackOverflow 问题中发现的 - Best way to parse command line arguments in C#?

MWE

using System;
using CommandLine;

namespace CLPtest
{
    class Program
    { 

        class SomeOptions
        {
            [Option('n', "name")]
            public string Name { get; set; }

        }

        static void Main(string[] args)
        {

            var options = new SomeOptions();

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

        }
    }
}

当我尝试创建一个最小的工作示例时,我在此行收到 options 错误:

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

错误是Argument 2: cannot convert from 'CLPtest.Program.SomeOptions' to 'System.Type'

我真的很困惑,因为我在至少 3 个关于如何使用这个库的教程中看到了相同的示例代码。 (例如 - Parsing Command Line Arguments with Command Line Parser Library

【问题讨论】:

  • This is the file that OP didn't link to。 ParseArguments() 有几个重载。我的建议是决定要调用哪一个,并传递正确类型的参数。自然,他们的代码不知道您的 SomeOptions 类。您链接的教程被我工作的防火墙阻止了,但也许其他人可以看看。
  • 我看过教程。也许有可能存在同名的不同 nuget 包,它恰好具有非常相似的界面,但是当我在 nuget 中搜索“CommandLineParser”时也没有出现。但这很牵强。本教程也有可能引用了已过时或尚未发布的库版本。事实上,当前版本 2.6.0 没有教程调用的方法。不幸的是,许多教程充其量是毫无价值的。
  • @EdPlunkett 好的,感谢您的调查。我下载的 nuget 包有 11M 的下载量,所以我猜它是“那个”。但是,是的,可能是教程现在已经过时了。
  • 我抽查了几个旧版本,没有一个有这样的方法。我想你可以都尝试一下,也许一两个人会吃到。

标签: c# .net command-line-arguments


【解决方案1】:

(这个答案是在这个库 v2.7 的时候写的)

their repository's README 看来,这似乎是自述文件中前面提到的 API 更改的一部分。与您引用的示例代码相比,现在似乎对参数的处理方式有所不同。所以,现在你应该在 Main 内部做这样的事情:

...

static void Main(string[] args)
{
    CommandLine.Parser.Default.ParseArguments<SomeOptions>(args);
}

...

要对这些选项进行实际操作,您可以使用WithParsed,它接受在您的SomeOptions 类中定义的选项。

...

static void Main(string[] args)
{
    CommandLine.Parser.Default.ParseArguments<SomeOptions>(args).WithParsed(option =>
    {
        // Do something with your parsed arguments in here...

        Console.WriteLine(option.Name); // This is the property from your SomeOptions class.
    });
}

...

自述文件后面的C# Example 表明您可以将一个方法传递给WithParsed 来处理您的选项,而不是在Main 中执行所有操作。

【讨论】:

    猜你喜欢
    • 2014-12-24
    • 2018-05-15
    • 2011-03-03
    • 2016-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-25
    • 2012-10-29
    相关资源
    最近更新 更多