How can I assign a string to an enum instead of an

2020-02-05 09:39发布

I am trying to assign a string to an enum. Something like the following example:

    enum MyEnum
    {
        frist = "First Value",
        second = "Second Value",
        third = "Third Value"
    }

So that I can have something like this in my code:

MyEnum enumVar = MyEnum.first;
...
string enumValue = EnumVar.ToString();//returns "First Value"

In conventional way when i create an Enum, the ToString() will return the enums name not its value.So it is not desirable since I am seeking a way to assign a string value and then get that string value out of an enum.

标签: c# enums
5条回答
做个烂人
2楼-- · 2020-02-05 10:04

The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong. so Like a string the only thing you can to is

enum MyEnum { first, second, third }

MyEnum.first.ToString();

or like using reflection and go using description as a attribute to the fields in the enum.

查看更多
Viruses.
3楼-- · 2020-02-05 10:19

You may add a Description attribute to your enum.

enum MyEnum
    {
        [Description("First Value")]
        frist, 
        [Description("Second Value")]
        second, 
        [Description("Third Value")]
        third,
    }

Then have a method to return you the description.

public static string GetEnumDescription(Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());

            DescriptionAttribute[] attributes =
                (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

            if (attributes != null && attributes.Length > 0)
                return attributes[0].Description;
            else
                return value.ToString();
        }

Then you can do:

   MyEnum enumVar = MyEnum.frist;
   string value = GetEnumDescription(enumVar);

value will hold "First Value"

You may see: Associating Strings with enums in C#

查看更多
▲ chillily
4楼-- · 2020-02-05 10:23
enum MyEnum
{
    FirstValue, //Default Value will be 0
    SecondValue, // 1
    ThirdValue // 2
}

string str1 = Enum.GetName(typeof(MyEnum), 0); //will return FirstValue
string str2 = Enum.GetName(typeof(MyEnum), MyEnum.SecondValue); //SecondValue

if you need a full string like with spaces, etc, you need to go by adding the Description approach. Else I recomment just creating a lookup dictionary.

     string value = MyLookupTable.GetValue(1); // First Value
     value = MyLookupTable.GetValue(2); // Second Value
     value = MyLookupTable.GetValue(3); // Third Value

class MyLookupTable
{
    private static Dictionary<int, string> lookupValue = null;

    private MyLookupTable() {}

    public static string GetValue(int key)
    {
        if (lookupValue == null || lookupValue.Count == 0)
            AddValues();

        if (lookupValue.ContainsKey(key))
            return lookupValue[key];
        else
            return string.Empty; // throw exception
    }

    private static void AddValues()
    {
        if (lookupValue == null)
        {
            lookupValue = new Dictionary<int, string>();
            lookupValue.Add(1, "First Value");
            lookupValue.Add(2, "Second Value");
            lookupValue.Add(3, "Third Value");
        }
    }
}
查看更多
爷、活的狠高调
5楼-- · 2020-02-05 10:24

You can't do that. enums are based on integers, not strings.

查看更多
Juvenile、少年°
6楼-- · 2020-02-05 10:25

You can't the value of an enum is always an integer

The closest you can come is a static class with a set of static properties

static class MyValues
{
    public static readonly string First = "First Value";
    public static readonly string Second = "Second Value";
    public static readonly string Third = "Third Value";
}
查看更多
登录 后发表回答