是否可以保证枚举的ToString的值是多少? [英] Is it possible to guarantee the value of what ToString for an enum will be?
问题描述
我正在使用的数据库当前有一个varchar字段,在我的代码中,我想将潜在值映射到一个枚举,例如:
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
是我可以这样做:
UserStatus.SuperUser.ToString()
并具有SUPERUSER的值,并且保持一致而不会使道路更糟吗?
And have that value be SUPERUSER, and this be consistant and not screw up down the road?
推荐答案
更好的解决方案可能是利用 DescriptionAttribute
:
A better solution may be to take advantage of the 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
的引用。完全是您的通话。
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.
这篇关于是否可以保证枚举的ToString的值是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!