首页 > 解决方案 > 如何使用 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作为输出。但是,相反,我想获得一个异常,因为该选项是必需的,并且我不希望枚举隐含的默认值。

标签: c#system.commandlinesystem.commandline.dragonfruit

解决方案


我不知道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 个字节)。


推荐阅读