String representation of an Enum

后端 未结 30 2285
不思量自难忘°
不思量自难忘° 2020-11-22 02:44

I have the following enumeration:

public enum AuthenticationMethod
{
    FORMS = 1,
    WINDOWSAUTHENTICATION = 2,
    SINGLESIGNON = 3
}

T

30条回答
  •  时光取名叫无心
    2020-11-22 03:11

    Well, after reading all of the above I feel that the guys have over complicated the issue of transforming enumerators into strings. I liked the idea of having attributes over enumerated fields but i think that attributes are mainly used for Meta-data, but in your case i think that all you need is some sort of localization.

    public enum Color 
    { Red = 1, Green = 2, Blue = 3}
    
    
    public static EnumUtils 
    {
       public static string GetEnumResourceString(object enumValue)
        {
            Type enumType = enumValue.GetType();
            string value = Enum.GetName(enumValue.GetType(), enumValue);
            string resourceKey = String.Format("{0}_{1}", enumType.Name, value);
            string result = Resources.Enums.ResourceManager.GetString(resourceKey);
            if (string.IsNullOrEmpty(result))
            {
                result = String.Format("{0}", value);
            }
            return result;
        }
    }
    

    Now if we try to call the above method we can call it this way

    public void Foo()
    {
      var col = Color.Red;
      Console.WriteLine (EnumUtils.GetEnumResourceString (col));
    }
    

    All you need to do is just create a resource file containing all the enumerator values and the corresponding strings

    Resource Name          Resource Value
    Color_Red              My String Color in Red
    Color_Blue             Blueeey
    Color_Green            Hulk Color
    

    What is actually very nice about that is that it will be very helpful if you need your application to be localized, since all you need to do is just create another resource file with your new language! and Voe-la!

提交回复
热议问题