一個更好的解決方案可能是利用的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
的引用。完全是你的電話。
如果你在控制代碼庫,那麼確定你可以確保。 –
['ToUpperInvariant()'](http://msdn.microsoft.com/en-us/library/system.string.toupperinvariant(v = vs.110).aspx)? – PoByBolek
你甚至可能不需要這個。你沒有指定你的SQL方言,但是其中的許多默認情況下對文本是不區分大小寫的,這意味着「SuperUser」會滿足約束條件。 – hvd