是否有可能保证枚举的ToString值?

时间:2013-12-16 20:14:24

标签: c# enumeration

我正在使用的数据库目前有一个varchar字段,在我的代码中我想将潜在值映射到枚举,如:

public enum UserStatus
{
    Anonymous,
    Enrolled,
    SuperUser
}

在此列的数据库级别,对其进行约束,其值必须为:

ANONYMOUS
ENROLLED
SUPERUSER

我可以这样做:

UserStatus.SuperUser.ToString()

并且这个价值是超级的,这是一致的,而不是搞砸了吗?

3 个答案:

答案 0 :(得分:7)

更好的解决方案可能是利用DescriptionAttribute

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

然后使用类似的东西:

/// <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);
    }
}

所以现在你引用了UserStatus.Anonymous.GetDescription()

当然,您可以随时制作自己的DatabaseMapAttribute(或者有什么),并创建自己的扩展方法。然后你可以杀死对System.ComponentModel的引用。完全是你的电话。

答案 1 :(得分:6)

您无法覆盖ToString枚举,而是可以创建自己的Extension Method,如:

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

然后称之为:

string str = UserStatus.Anonymous.ToUpperString();

答案 2 :(得分:1)

Enum.ToString支持4 different formats。我会去:

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

“G”确保它首先尝试获取枚举的字符串表示。

相关问题