如何使用System.CommandLine.DragonFruit将枚举定义为CLI选项



我想在C#System.CommandLine.DragonFruit中将枚举定义为CLI选项;内置";支持这个用例?详细地说,我需要一个相当于Python的click实现:

@click.option('-m', '--mode', required=True, type=click.Choice(['SIM_MRM', 'SPECTRUM'], case_sensitive=True), help="The measurement mode.")

如果我在C#控制台应用程序中定义以下内容

using System;
namespace EndDeviceAgent
{
class Program
{
enum MeasurementMode : short
{
SIM_MRM,
SPECTRUM
}
/// <param name="mode">The measurement mode.</param>
static void Main(MeasurementMode mode)
{
Console.WriteLine($"Mode: {mode}");
}
}
}

我得到Mode: SIM_MRM作为输出。但是,我希望得到一个异常,因为该选项是必需的,并且我不希望枚举隐含默认值。

我不知道System.CommandLine,但一个简单的方法可能是在枚举中添加一个默认值,并在开始时检查模式以抛出异常:

enum MeasurementMode
{
NONE,
SIM_MRM,
SPECTRUM
}
static void Main(MeasurementMode mode)
{
if ( mode == MeasurementMode.None ) 
throw new ArgumentException("A mode value other than NONE must be provided.");
Console.WriteLine($"Mode: {mode}");
}

也许存在更好的解决方案,例如应用需求的属性,这样您就可以在有时间的情况下检查文档或源代码。

我删除了short关键字,因为它不需要,除非你有充分的理由使用它(在任何x32/x64系统上,默认情况下都需要4个字节(。

枚举现在在System.Commandline 中受支持

";枚举类型的值由名称绑定,并且绑定不区分大小写:https://learn.microsoft.com/en-us/dotnet/standard/commandline/model-binding

Olivier Rogier的回答没有错,使用初始NONE值也是我的第一个想法。我想提供一个替代方案:使用Nullable类型。这也可以与其他简单的值类型(如int(一起使用,以强制用户显式提供值。

static void Main(Nullable<MeasurementMode> mode)
{
if (!mode.HasValue) 
throw new ArgumentException("A mode value must be provided.");
Console.WriteLine($"Mode: {mode.Value}");
}

或等效但更短的

static void Main(T? mode)
{
if (mode == null) 
throw new ArgumentException("A mode value must be provided.");
Console.WriteLine($"Mode: {mode.Value}");
}

最新更新