使用 CommandLineParser NuGet,当我在没有参数的情况下运行我的应用程序时,是否可以强制显示 --help 结果输出,就像我要运行我的应用程序一样...
myapplication.exe --help
目前,当我运行我的应用程序时,如果我未指定任何选项,它不会显示帮助输出。它只是结束应用程序。我有许多不同的选项/标志/参数可以使用。他们都不应该被自己强迫,但我至少需要一个被使用或显示帮助。
我目前的实施...
public class Options
{
[Option(
'v',
Required = false,
HelpText = "Shows all debug information when processing."
)]
public bool Verbose { get; set; }
[Option(
Required = false,
HelpText = "Runs Test One."
)]
public bool TestOne { get; set; }
}
static void Main(string[] args)
{
try
{
var parserResults = Parser.Default.ParseArguments<Options>(args);
parserResults
.WithParsed<Options>(options => Run(options));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.WriteLine("Main thread closing.");
}
static void Run(Options options)
{
// Verbose mode
if (options.Verbose)
{
m_Verbose = true;
Console.WriteLine("Verbose mode on.");
}
// Test
if (options.TestOne)
{
//do test
}
}
我能够使用这两个技巧来完成这项工作:
这是一些示例代码:
using CommandLine;
using CommandLine.Text;
internal static class Main
{
public static void Main(string[] Arguments)
{
HelpText oHelpText;
ParserResult<Command.Options> oResult;
oResult = Parser.Default.ParseArguments<Command.Options>(Arguments);
oResult.Success(Options => Run(Options));
oHelpText = HelpText.AutoBuild(oResult, x => x, x => x);
Console.WriteLine(oHelpText);
Console.ReadLine();
}
private static void Run(Command.Options Options)
{
switch (Options.Type)
{
case Command.Types.Folder:
{
break;
}
case Command.Types.File:
{
break;
}
}
}
}
internal static class Extensions
{
public static ParserResult<Command.Options> Success(this ParserResult<Command.Options> Instance, Action<Command.Options> Action)
{
return Instance.WithParsed(Action);
}
public static ParserResult<Command.Options> Failure(this ParserResult<Command.Options> Instance, Action<Command.Options> Action)
{
return Instance.WithNotParsed(Action);
}
}
namespace Command
{
internal class Options
{
[Option("s", "source", HelpText = "The source folder that contains the designated files/subfolders")]
public string Source { get; set; }
[Option("t", "target", HelpText = "The target folder to which to move the files/subfolders")]
public string Target { get; set; }
[Option("y", "type", HelpText = "The source type [File | Folder]")]
public Enums.Types Type { get; set; }
[Option("c", "chunksize", HelpText = "The size of each chunk to move")]
public int ChunkSize { get; set; }
}
internal static class Enums
{
public enum Types
{
Folder,
File
}
}
}
是的,只需将以下内容添加为 Main 方法的前两行:
if (args.Length == 0)
args = new [] { "--help" };