Is it possible to guarantee the value of what ToString for an enum will be?

时间秒杀一切 提交于 2019-12-10 02:23:38

问题


The database I am working with currently has a varchar field, and in my code I want to map the potential values to a enumeration like:

public enum UserStatus
{
    Anonymous,
    Enrolled,
    SuperUser
}

At the database level for this column, there is a constrain on it where the value has to be:

ANONYMOUS
ENROLLED
SUPERUSER

Is it possible for me to do:

UserStatus.SuperUser.ToString()

And have that value be SUPERUSER, and this be consistant and not screw up down the road?


回答1:


A better solution may be to take advantage of the DescriptionAttribute:

public enum UserStatus
{
    [Description("ANONYMOUS")]
    Anonymous,
    [Description("ENROLLED")]
    Enrolled,
    [Description("SUPERUSER")]
    SuperUser
}

Then use something like:

/// <summary>
/// Class EnumExtenions
/// </summary>
public static class EnumExtenions
{
    /// <summary>
    /// Gets the description.
    /// </summary>
    /// <param name="e">The e.</param>
    /// <returns>String.</returns>
    public static String GetDescription(this Enum e)
    {
        String enumAsString = e.ToString();
        Type type = e.GetType();
        MemberInfo[] members = type.GetMember(enumAsString);
        if (members != null && members.Length > 0)
        {
            Object[] attributes = members[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (attributes != null && attributes.Length > 0)
            {
                enumAsString = ((DescriptionAttribute)attributes[0]).Description;
            }
        }
        return enumAsString;
    }

    /// <summary>
    /// Gets an enum from its description.
    /// </summary>
    /// <typeparam name="TEnum">The type of the T enum.</typeparam>
    /// <param name="description">The description.</param>
    /// <returns>Matching enum value.</returns>
    /// <exception cref="System.InvalidOperationException"></exception>
    public static TEnum GetFromDescription<TEnum>(String description)
        where TEnum : struct, IConvertible // http://stackoverflow.com/a/79903/298053
    {
        if (!typeof(TEnum).IsEnum)
        {
            throw new InvalidOperationException();
        }
        foreach (FieldInfo field in typeof(TEnum).GetFields())
        {
            DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
            if (attribute != null)
            {
                if (attribute.Description == description)
                {
                    return (TEnum)field.GetValue(null);
                }
            }
            else
            {
                if (field.Name == description)
                {
                    return (TEnum)field.GetValue(null);
                }
            }
        }
        return default(TEnum);
    }
}

So now you're referencing UserStatus.Anonymous.GetDescription().

Of course you could always make your own DatabaseMapAttribute (or what-have-you) and create your own extension methods. Then you can kill a reference to System.ComponentModel. Completely your call.




回答2:


You can't override ToString for enums, instead you can create your own Extension Method like:

public static class MyExtensions
{
    public static string ToUpperString(this UserStatus userStatus)
    {
        return userStatus.ToString().ToUpper();// OR .ToUpperInvariant 
    }
}

And then call it like:

string str = UserStatus.Anonymous.ToUpperString();



回答3:


Enum.ToString supports 4 different formats. I'd go for:

UserStatus.SuperUser.ToString("G").ToUpper();

"G" ensures that it will try first to get the string representation of your enum.



来源:https://stackoverflow.com/questions/20620032/is-it-possible-to-guarantee-the-value-of-what-tostring-for-an-enum-will-be

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!