c# - HelpVerbOption 不工作 - 命令行解析器 C#

标签 c# command-line command-line-arguments command-line-parser

我有一个类:

class Options
{
    // Remainder omitted (verb1, verb2, verb3)
    [HelpVerbOption]
    public string GetUsage(string verb)
    {
        return HelpText.AutoBuild(this, verb);
    }
}

docs说:

[...] The parser will pass null to master class GetUsage(string) also if the user requested the help index with:

$ git help

or the verb command if the user requested explicitly instructions on how to use a particular verb:

$ git help commit

[...]

然后,我输入了 MyApp.exe help verb1,但我只能看到基本帮助(看起来我输入了错误的动词,或者 help 动词,或者某物)。相反,我希望它显示与指定动词相关的帮助消息。为什么它不能正常工作?

最佳答案

对我来说,它可以使用上述方法工作,但前提是我调用我的应用程序时不使用 --help-选项(例如 MyApp batch)。当我使用 MyApp --help batch 时,行为如您所述。

但是,我们似乎无法为 help 选项获得相同的效果。

编辑:我设法通过使用以下代码修改 Commandline.Parser.cs 的代码来实现此功能:

private bool TryParseHelpVerb(string[] args, object options, Pair<MethodInfo, HelpVerbOptionAttribute> helpInfo, OptionMap optionMap)
{
    var helpWriter = _settings.HelpWriter;
    if (helpInfo != null && helpWriter != null)
    {
        if (string.Compare(args[0], helpInfo.Right.LongName, GetStringComparison(_settings)) == 0)
        {
            // User explicitly requested help
            var verb = args.FirstOrDefault(); // <----- change this to args[1];
            if (verb != null)
            {
                var verbOption = optionMap[verb];
                if (verbOption != null)
                {
                    if (verbOption.GetValue(options) == null)
                    {
                        // We need to create an instance also to render help
                        verbOption.CreateInstance(options);
                    }
                }
            }
            DisplayHelpVerbText(options, helpInfo, verb);
            return true;
        }
    }

    return false;
}

问题出现在行

var verb = args.FirstOrDefault();

因为第一个参数 (args[0]) 被解释为动词或更好的action(如文档中所述)verb 将永远是 help 在这里。因此,我们将其替换为 args[1],其中包含 actual 动词,例如 commit

EDIT2:为了让 --help 工作,我们还应该从 - 中修剪第一个 arg (args[0]) >-字符

if (string.Compare(args[0].Trim('-'), helpInfo.Right.LongName, GetStringComparison(_settings)) == 0)

关于c# - HelpVerbOption 不工作 - 命令行解析器 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39079282/

相关文章:

c# - 将字符串拆分(不解析)为命令行参数 C#

python - 为什么 args.add_argument 在两个单独的语句中给出而不是在 python 中给出?

c# - 使用 IronPython 通过 C# .NET 导入 Python 模块

c# - 使用 MVVM 构建选项列表

node.js - 无法将命令行参数传递给全局安装的 Node 包到 bin 快捷方式

c++ - 为什么这段代码不运行?

c# - 为什么 Nullable<T> HasValue 属性不会在 Null 上抛出 NullReferenceException?

c# - 从输入中减去输出音频流

mysql - 如何在 MySQL 中运行 SQL 脚本?

c# - 查看 c# 控制台应用程序参数