【发布时间】:2017-02-26 09:04:00
【问题描述】:
这个问题是关于 .net core 中的一系列类一起工作以提供丰富的命令行解析经验。主类是CommandLineApplication。 This是一篇走过主要设施的文章。
这是配置显示自动生成帮助的帮助选项的方式。
cla.HelpOption("-? | -h | --help");
如果在命令行的任何位置找到帮助选项,我希望我的应用程序终止,而不是继续运行。但我找不到实现这一目标的好方法。我当然可以自己解析参数以查找是否指定了选项,但这不是为我执行此功能的全部意义吗?
这是我正在使用的示例代码:
public class Config
{
public string Option1 {get; set;}
}
public class CommandLine
{
public static void ApplyCommandLineArguments(string[] args, Config config)
{
CommandLineApplication cla = new CommandLineApplication(false);
CommandOption option1 = cla.Option(
"-o | --option1",
"Set this option to specify option1",
CommandOptionType.SingleValue
);
cla.HelpOption("-? | -h | --help");
cla.OnExecute(() =>
{
if (option1.HasValue())
{
config.Option1 = option1.Value();
}
return 0;
});
try
{
cla.Execute(args);
}
catch (CommandParsingException ex)
{
Console.WriteLine(ex.Message);
cla.ShowHelp();
}
}
}
然后在Main方法中:
Config config = new Config();
CommandLine.ApplyCommandLineArguments(args, config);
// I want to exit here if user specified the help option anywhere on the command line.
Console.WriteLine("Hello World!");
【问题讨论】:
-
只看它,我会说您似乎应该执行
if (option1.HasValue())中的代码(或将其设置为config.Option1 = true,然后在您的主代码中检查)。跨度> -
@VisualVincent,这对我来说很明显,但是
option1的价值在这里有什么帮助呢?我错过了什么? -
我不知道该库是如何工作的,但是通过查看它,当其中一个命令存在时,
option1.HasValue()似乎返回true。然后它将config.Option1设置为该值。您是否尝试过使用调试器检查变量? -
@VisualVincent,对不起,我的意思是,我的问题不在于设置或检查 Option1 存储或设置的任何内容。因此,我看不出这会如何使我们更接近目标。
-
如果命令行包含“帮助”选项,您想终止应用程序,对吗?为此,您必须知道哪个变量或方法可以告诉您它确实如此,并且由于我不知道这个库是如何工作的,所以我能做的就是从我的角度给出建议。
标签: c# command-line .net-core