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

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

public enum UserStatus { Anonymous, Enrolled, SuperUser } 

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

 ANONYMOUS ENROLLED SUPERUSER 

我有可能这样做:

 UserStatus.SuperUser.ToString() 

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

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

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

然后使用类似的东西:

 ///  /// Class EnumExtenions ///  public static class EnumExtenions { ///  /// Gets the description. ///  /// The e. /// String. 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; } ///  /// Gets an enum from its description. ///  /// The type of the T enum. /// The description. /// Matching enum value. ///  public static TEnum GetFromDescription(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的引用。 完全是你的电话。

您不能为枚举覆盖ToString ,而是可以创建自己的扩展方法,如:

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

然后称之为:

 string str = UserStatus.Anonymous.ToUpperString(); 

Enum.ToString支持4种不同的格式 。 我会去:

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

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