C# numeric enum value as string

前端 未结 8 1150
隐瞒了意图╮
隐瞒了意图╮ 2020-12-07 18:34

I have the following enum:

public enum Urgency {
    VeryHigh = 1,
    High     = 2,
    Routine  = 4
}

I can fetch an enum \"value

相关标签:
8条回答
  • 2020-12-07 19:15

    Great stuff ... I have now added an extension method to my project

    public static class EnumExtensions 
    { 
        public static string NumberString(this Enum enVal) 
        { 
            return enVal.ToString("D"); 
        }
    } 
    

    Now I can get the int value - as a string - by calling Urgency.Routine.NumberString(); Thanks to Frankentosh and Jon :)

    0 讨论(0)
  • 2020-12-07 19:15

    If you wanted, you could make the extension method work for all enums:

    public static string ToValueString(this Enum enumValue) 
    {
        if (enumValue.GetType().GetEnumUnderlyingType() == typeof(int))
            return ((int)(object)enumValue).ToString();
        else if (enumValue.GetType().GetEnumUnderlyingType() == typeof(byte))
            return ((byte)(object)enumValue).ToString();
        ... 
    }        
    
    0 讨论(0)
提交回复
热议问题