An enumeration set to a string and, if necessary, gets a twist value

I do not know how to do this.
I want the code to look like this

enum myenum
{
    name1 = "abc",
    name2 = "xyz"
}

and check it out

if (myenum.name1 == variable)

How can i do this?

thank.

+5
source share
5 answers

Unfortunately this is not possible. Transfers can have only the basic base type ( int, uint, shortetc.). If you want to associate enumeration values ​​with additional data, apply attributes to the values ​​(for example, DescriptionAttribute).

public static class EnumExtensions
{
    public static TAttribute GetAttribute<TAttribute>(this Enum value)
        where TAttribute : Attribute
    {
        var type = value.GetType();
        var name = Enum.GetName(type, value);
        return type.GetField(name)
            .GetCustomAttributes(false)
            .OfType<TAttribute>()
            .SingleOrDefault();
    }

    public static String GetDescription(this Enum value)
    {
        var description = GetAttribute<DescriptionAttribute>(value);
        return description != null ? description.Description : null;
    }
}

enum MyEnum
{
    [Description("abc")] Name1,
    [Description("xyz")] Name2,
}

var value = MyEnum.Name1;
if (value.GetDescription() == "abc")
{
    // do stuff...
}
+12
source

, , . , , , , , , - :

class Constants
{
    public static string name1 = "abc";
    public static string name2 = "xyz";
}

...

if (Constants.name1 == "abc")...
+4

, . : . , , . , , , .

0

, , , , enum s.

0

Good answers here. Clarifying the proposed answer is that you would rather get the value of the enumeration, given the description of the enumeration . I have not tested this, but this may work:

Enum:

public enum e_BootloadSource : byte
{
    [EnumMember]
    [Display(Name = "UART")]
    [Description("UART_BL_RDY4RESET")]
    UART = 1,
    [EnumMember]
    [Display(Name = "SD")]
    [Description("SD_BL_RDY4RESET")]
    SD = 2,
    [EnumMember]
    [Display(Name = "USB")]
    [Description("USB_BL_RDY4RESET")]
    USB = 3,
    [EnumMember]
    [Display(Name = "Fall Through Mode")]
    [Description("FALL_THRGH_BL_RDY4RESET")]
    FALL_THROUGH_MODE = 4,
    [EnumMember]
    [Display(Name = "Cancel Bootload")]
    [Description("BL_CANCELED")]
    CANCEL_BOOTLOAD = 5,
}

Use the following:

foreach(e_BootloadSource BLSource in Enum.GetValues(typeof(e_BootloadSource)))
                    {
                        if (BLSource.GetDescription() == inputPieces[(int)SetBLFlagIndex.BLSource])
                        {
                            newMetadata.BootloadSource = BLSource;
                        }
                    }

Note. The input elements are a purely string array, and newMetadata.BootloadSource is e_BootloadSource.

0
source

All Articles