[英]Is it possible to guarantee the value of what ToString for an enum will be?
我正在使用的數據庫目前有一個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
}
然后使用類似的東西:
/// <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
的引用。 完全是你的電話。
您不能為枚舉覆蓋ToString
,而是可以創建自己的擴展方法,如:
public static class MyExtensions
{
public static string ToUpperString(this UserStatus userStatus)
{
return userStatus.ToString().ToUpper();// OR .ToUpperInvariant
}
}
然后把它稱為:
string str = UserStatus.Anonymous.ToUpperString();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.