c# - 如何使用 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 个字节)。
推荐阅读
- c++ - 无法通过 Linux 和 C++ 在串行通信中通过 read() 从设备接收消息
- java - 使用 xmlMapper (java) 反序列化 xml 时的问题
- elasticsearch - 应用排序字段后,弹性搜索结果得分为 0
- matrix - Power Bi 计算上个月的增长并在矩阵中显示
- swift - arkit 3d bodytracking 镜子倒置
- docker - 从 PgAdmin4 5.7 中的存储管理器下载文件时出错
- elasticsearch - 如何防止elasticsearch模糊搜索对重复词给出高分
- typescript - 将值数组映射到 Typescript 中的泛型类型
- python - 使用 jinja 2 变量更新 Yaml
- ruby-on-rails - Bundler 不会在 docker 上加载 puma