将枚举名称分配给const变量

时间:2015-01-19 15:54:23

标签: c# enums

我目前正在尝试将特定枚举中的名称分配给字符串,以便我可以在输出到控制台的帮助文档中使用它。这很容易做到:

public string names = string.Join(", ", Enum.GetNames(typeof(LicenseType)));

我的问题是我正在使用Command Line Parser Library,这需要将每个选项的帮助文本指定为属性参数(HelpText),它必须是“常量表达式,typeof表达式或数组创建表达式的属性参数类型“。如何使用names的示例:

[Option('t', "license-type", Required = true, HelpText = names)]

但是,当我尝试使用上面的代码将枚举名称分配给const string时,编译器会抱怨表达式不是常量。

有什么方法吗?

3 个答案:

答案 0 :(得分:1)

问题在于即使enum可能是编译时常量,任何代码,包括实际获取这些名称的上述代码,不是不变,因为它需要评估而不仅仅是原始的。因此,无法在enum中使用期望Attribute的{​​{1}}名称。

但是,如果string不是OptionAttribute,您可以定义一个继承的sealed类,它接受欲望枚举的参数,然后将上面的代码传递给{{ 1}}。使用此Attribute,即使您已将base(string)值传递给Attribute,该库也应将其视为OptionAttribute。请参阅以下代码:

enum

可悲的是,已经注意到public class EnumHelpTextAttribute // Always postpend the word "Attribute" to an attribute class // The compiler cleans this suffix when you actually use the Attribute : OptionAttribute { public EnumHelpTextAttribute(LicenseType value) : base(string.Join(", ", Enum.GetName(typeof(LicenseType), value))) { } } // ... [EnumHelpText(LicenseType.Restricted)] // Or some other value in LicenseType... OptionAttribute,这会阻止创建继承者。然而,作为一个开源项目,可以分叉源,解开类,并因此使用上述建议。与往常一样,记录使用情况并提出拉回请求 - 这可以轻松地为其他人节省一天的麻烦!

答案 1 :(得分:0)

枚举是编译时常量,但编译器无法保证对string.Join的方法调用将产生常量值,因为它与Enum.GetName一起使用。

由于您的枚举是一个常量编译,您需要将值硬编码为属性。

答案 2 :(得分:0)

昨晚睡觉之后,解决方案实际上非常明显(总是这样!):只是使用字符串替换......

class Options
{
    private static string LicenseTypeHelp = "License type (" + string.Join(", ", Enum.GetNames(typeof(CompanyLicenseType))) + ").";

    [Option('t', "license-type", Required = true, HelpText = "License type.")]
    public CompanyLicenseType LicenseType { get; set; }    

    [HelpOption('h', "help", HelpText = "Dispaly this help screen.")]
    public string GetUsage()
    {
        string helpText = HelpText.AutoBuild(this, current => HelpText.DefaultParsingErrorsHandler(this, current));
        return helpText.Replace("License type.", LicenseTypeHelp);
    }
}
相关问题