You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在System.CommandLine中排除枚举值及实现字符串与枚举映射?

System.CommandLine枚举选项定制问题

我定义了如下System.CommandLine选项(LogLevel为枚举类型):

private static readonly Option<LogLevel> option = new(new[] { "--logLevel" })
{
    Description = "The severity (log level)."
};

自动生成的帮助文档会将所有枚举值列为--logLevel的有效值:

return (<Debug|Detailed|Error|Fatal|Info|Off|Silent|Warning>
)

请问能否通过System.CommandLine禁止部分枚举值,或是实现字符串与枚举值的映射(例如将"W"映射至Warning枚举值)?


一、禁止部分枚举值

可以通过配置选项的AllowedValues属性,指定仅允许的枚举值,这样既会在帮助文档中只展示指定值,也会拦截用户输入的未授权值:

private static readonly Option<LogLevel> option = new(new[] { "--logLevel" })
{
    Description = "The severity (log level).",
    // 仅保留需要开放的枚举值
    AllowedValues = new List<LogLevel> { LogLevel.Debug, LogLevel.Info, LogLevel.Warning, LogLevel.Error }
};

当用户输入未在列表中的枚举值时,System.CommandLine会自动返回错误提示,告知合法的可选值。

二、实现字符串与枚举值的自定义映射

要实现自定义字符串(如"W")到枚举值的映射,需要自定义ArgumentConverter来处理输入转换:

  1. 先创建自定义转换器类:
public class LogLevelConverter : ArgumentConverter<LogLevel>
{
    public override LogLevel Convert(ArgumentConversionContext context)
    {
        string input = context.Tokens.Single().Value.ToLowerInvariant();
        // 定义自定义缩写与枚举值的映射
        return input switch
        {
            "w" => LogLevel.Warning,
            "i" => LogLevel.Info,
            "d" => LogLevel.Debug,
            "e" => LogLevel.Error,
            // 其他情况回退到默认枚举解析(支持大小写忽略)
            _ => Enum.Parse<LogLevel>(input, ignoreCase: true)
        };
    }
}
  1. 在选项中绑定该转换器:
private static readonly Option<LogLevel> option = new(new[] { "--logLevel" })
{
    Description = "The severity (log level). 支持缩写:Debug(d), Info(i), Warning(w), Error(e)",
    AllowedValues = new List<LogLevel> { LogLevel.Debug, LogLevel.Info, LogLevel.Warning, LogLevel.Error },
    ArgumentConverter = new LogLevelConverter()
};

这样用户既可以输入完整的枚举名称,也可以使用自定义缩写,帮助文档也能清晰说明可用的输入方式。

内容的提问来源于stack exchange,提问作者hardfork

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 18:01:09