C#枚举返回带有中断的字符串

Tom*_*len 1 c# asp.net enums

我需要我的枚举返回一个特定的字符串,但我无法弄清楚如何让它返回一个包含中断的字符串而无需进行转换的方法.没有辅助方法可以LicenseTypes.DISCOUNT_EARLY_ADOPTER返回DISCOUNT EARLY-ADOPTER吗?

// All license types
public enum LicenseTypes
{
    DISCOUNT,
    DISCOUNT_EARLY_ADOPTER,
    COMMERCIAL,
    COMMERCIAL_EARLY_ADOPTER
}

// Convert enum to correct string
public static string LicenseTypeToString(LicenseTypes Enum)
{
    if (Enum == LicenseTypes.COMMERCIAL)
        return "COMMERCIAL";
    else if (Enum == LicenseTypes.COMMERCIAL_EARLY_ADOPTER)
        return "COMMERCIAL EARLY-ADOPTER";
    else if (Enum == LicenseTypes.DISCOUNT)
        return "DISCOUNT";
    else if (Enum == LicenseTypes.DISCOUNT_EARLY_ADOPTER)
        return "DISCOUNT EARLY-ADOPTER";
    else
        return "ERROR";
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 8

首先,辅助方法的一个单独选项就是让Dictionary<LicenseTypes, string>你填充一次.说实话,这可能是最简单的方法:

private static readonly Dictionary<LicenseTypes, string> LicenseDesciptions =
    new Dictionary<LicenseTypes, string> 
{
    { LicenseTypes.COMMERCIAL, "COMMERCIAL" },
    { LicenseTypes.COMMERCIAL_EARLY_ADOPTER, "COMMERCIAL EARLY-ADOPTER" },
    { LicenseTypes.DOMESTIC, "DOMESTIC" },
    { LicenseTypes.DOMESTIC_EARLY_ADOPTER, "DOMESTIC EARLY-ADOPTER" },
};
Run Code Online (Sandbox Code Playgroud)

(正如评论中所指出的,另一种选择是交换机/案例......但我个人更喜欢这种方式,因为有效地你有数据映射,所以使用数据结构而不是执行流结构是有意义的.也意味着如果你愿意,你可以换掉不同语言的词典等.)

其次,一个选项是用[Description]属性(或你想要的自己的属性)装饰每个枚举值,并用反射找出它 - 无约束的旋律有一个扩展方法,可以很容易地做到这一点:

// Throws ArgumentOutOfRangeException if the licenseType value isn't defined
// or doesn't have a description.
string description = licenseType.GetDescription();
Run Code Online (Sandbox Code Playgroud)

此外,遵循.NET命名约定,它应该是:

public enum LicenseType // Singular as it's not a Flags enum
{
    Discount,
    DiscountEarlyAdopter,
    Commercial,
    CommercialEarlyAdopter
}
Run Code Online (Sandbox Code Playgroud)