简体   繁体   中英

C# Enum return string with breaks

I need my enum to return a specific string, but I can't work out how to make it return a string with breaks in it without having a method to do the conversion. Is it possible to make LicenseTypes.DISCOUNT_EARLY_ADOPTER return DISCOUNT EARLY-ADOPTER without the helper method?

// 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";
}

Firstly, a separate option from a helper method is simply to have a Dictionary<LicenseTypes, string> which you populate once. That would probably be the simplest approach, to be honest:

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" },
};

(As noted in comments, another alternative is a switch/case... but I personally prefer this way, as effectively you've got a data mapping, so it makes sense to use a data structure rather than an execution flow structure. It also means you can swap out dictionaries for different languages etc if you want.)

Secondly, one option would be to decorate each enum value with a [Description] attribute (or your own attribute if you want), and find that out with reflection - Unconstrained Melody has an extension method which can do that very easily:

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

Also, following .NET naming conventions it should be:

public enum LicenseType // Singular as it's not a Flags enum
{
    Discount,
    DiscountEarlyAdopter,
    Commercial,
    CommercialEarlyAdopter
}

A little reflection, and Attribute magic, and this should just answer it :)
Getting attributes of Enum's value

Might also make it an extension method .

here's how it should look (also added generics):

public static class MyExtensionsClass
{
    public static string ToDescriptionString<T>(this T val)
        where T : struct, IConvertible
    {
        if (typeof(T).IsEnum) 
        {
           var type = val.GetType();
           var memInfo = type.GetMember(val.ToString());
           var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
           return ((DescriptionAttribute)attributes[0]).Description;
        }
        return ""; //all paths must return a value
    }
}

public enum LicenseTypes
{
    [Description("DISCOUNT")]
    DISCOUNT,
    [Description("DISCOUNT EARLY-ADOPTER")]
    DISCOUNT_EARLY_ADOPTER,
    [Description("COMMERCIAL")]
    COMMERCIAL,
    [Description("COMMERCIAL EARLY-ADOPTER")]
    COMMERCIAL_EARLY_ADOPTER
}

Thank you, guys that wrote these:

Good luck!

While it doesn't eliminate the helper method, note that in your case you could just special-case the values that you can't get using ToString :

switch (Enum) {
    case LicenseTypes.COMMERCIAL_EARLY_ADOPTER:
        return "COMMERCIAL EARLY-ADOPTER";
    case LicenseTypes.DISCOUNT_EARLY_ADOPTER:
        return "DISCOUNT EARLY-ADOPTER";
    default
        return Enum.ToString();
}

I use this from Google's dotnet client - StringValueAttribute.cs and Utilities.cs

public enum LicenseType
{
     [StringValue("DISCOUNT")] Discount,
     [StringValue("DISCOUNT EARLY-ADOPTER")] DiscountEarlyAdopter,
     [StringValue("COMMERCIAL")] Commercial,
     [StringValue("COMMERCIAL EARLY-ADOPTER")] CommercialEarlyAdopter
}

Then you can simply do this:

licenseType.GetStringValue();

Convert to string using "G" format, then replace "_" (underscore) with spaces:

LicensceTypes license = LicenseTypes.COMMERCIAL_EARLY_ADOPTERS;
string licenseDescription = license.ToString("G").Replace('_', ' ');
// licenseDescription = "COMMERCIAL EARLY ADOPTERS"

I think I would use a class to avoid this scenario. :/

public class LicenceType
{
    private string name;
    public LicenceType(string Name)
    {
        this.name = Name;
    }
    public override string ToString()
    {
        return name;
    }
}

public static class LicenceTypes
{
    public static LicenceType DISCOUNT = new LicenceType("DISCOUNT");
    public static LicenceType DISCOUNT_EARLY_ADOPTER= new LicenceType("DISCOUNT EARLY-ADOPTER");
    public static LicenceType COMMERCIAL= new LicenceType("COMMERCIAL");
    public static LicenceType COMMERCIAL_EARLY_ADOPTER= new LicenceType("COMMERCIAL EARLY-ADOPTER");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM