【问题标题】:Why does ManyConsole display public members of a CommandLine class?为什么 ManyConsole 显示 CommandLine 类的公共成员?
【发布时间】:2013-04-22 05:15:12
【问题描述】:

我使用ManyConsole 作为控制台应用程序的命令行命令和选项解析器。所有的命令都定义为从ConsoleCommand派生的命令类,然后实现特定的任务。我定义了一个中间基类,ParkPayConsoleCommand 派生自该类:

abstract class ParkPayConsoleCommand: ConsoleCommand
{
    protected readonly ParkPayDbContext DbContext = new ParkPayDbContext();
}

然后我所有的命令类都派生自我的基类,并享受内置的DbContext,例如:

class ReadStartsCommand : ParkPayConsoleCommand
{
    public ReadStartsCommand()
    {
        _commandTrace = new TraceSource(CommandName, SourceLevels.All);
        IsCommand("read-starts", "Processes imported vehicle entry movements to create new VehiclePresence records with start date-times based on those movements");
        HasRequiredOption("b|batchId:", "The Id of the VehicleMovementBatch used to create new vehicle presences.", b => _batchIdOption = b);
    }

    public override int Run(string[] remainingArguments)
    {
        // Do the business of the command.
        return (int)ExitCodes.Success;
    }
}

如上所示,每个命令类都命名和描述自身,并在其构造函数中定义其命令行选项,这是一个 ManyConsole 约定。通常,当我运行诸如上面的ReadStartsCommand 之类的命令时,它只会向控制台写入正在运行的命令,而不是我传递的选项。

然而,当我将ParkPayConsoleCommand.DbContext 设为公开,不受保护时,它会输出字符串

DbContext : ParkPay.Model.Context.ParkPayDbContext

到控制台末尾的运行命令的名称和描述。当DbContext 没有在任何地方定义为命令选项本身时,为什么它会这样做。这可能看起来微不足道,但本质上我问的是一个非常重要的“元问题”,那就是:ManyConsole 是否将其命令类的所有公共属性隐式解释为命令选项,即使它们没有明确声明为命令选项?

【问题讨论】:

    标签: c# command-line-interface console-application ndesk.options manyconsole


    【解决方案1】:

    我无法说出最初的意图,但正如您所发现的,是的,它似乎是这样做的。关于为什么这可能有用的建议:

    有时命令行选项不会一对一映射到ConsoleCommand 类的属性。考虑

    public class VerbosityCommand : ConsoleCommand
    { 
        public int VerbosityLevel {get;set;}
    
        public VerbosityCommand(){
             this.IsCommand("Verbosity","Control the level of verbosity");
             this.HasOption("v|verbose","Increase verbosity, cumulative",x => Verbosity++);
        }
    }
    

    现在,ManyConsole 打印的块将(有帮助地)有VerbosityLevel : 3(例如)而不是(无用地)有

    Verbose : set
    Verbose : set
    Verbose : set
    

    或类似的东西。

    另一个例子是预设类型标志,它将许多属性配置到通用配置中。

    在您的情况下,将_batchIdOption 设为公共和ParkPayDbContext 保护或私有可能会很有用。

    【讨论】:

      【解决方案2】:

      基本上是的,所有公共属性都如 Greg 所说的那样打印。这并不意味着它们都被视为参数(它们不是)。补充几点:

      • 如果您执行任何覆盖 OverrideAfterHandlingArgumentsBeforeRun() 的工作并将结果分配给公共成员,则该结果将在命令打印到控制台时显示。这对于为用户记录一些中间结果很有用

      • 要格式化成员的打印方式,您可以覆盖公共成员类型上的 ToString

      我希望在其他情况下使用 ManyConsole 很顺利。

      【讨论】:

        猜你喜欢
        • 2012-01-24
        • 1970-01-01
        • 2018-10-14
        • 2012-05-10
        • 1970-01-01
        • 2021-07-18
        • 2011-11-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多