我正在使用的数据库目前有一个varchar字段,在我的代码中我想将潜在的值映射到枚举,如:
public enum UserStatus
{
Anonymous,
Enrolled,
SuperUser
}
Run Code Online (Sandbox Code Playgroud)
在此列的数据库级别,对其进行约束,其值必须为:
ANONYMOUS
ENROLLED
SUPERUSER
Run Code Online (Sandbox Code Playgroud)
我有可能这样做:
UserStatus.SuperUser.ToString()
Run Code Online (Sandbox Code Playgroud)
并且这个价值是超级的,这是一致的,而不是搞砸了吗?
更好的解决方案可能是利用DescriptionAttribute:
public enum UserStatus
{
[Description("ANONYMOUS")]
Anonymous,
[Description("ENROLLED")]
Enrolled,
[Description("SUPERUSER")]
SuperUser
}
Run Code Online (Sandbox Code Playgroud)
然后使用类似的东西:
/// <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);
}
}
Run Code Online (Sandbox Code Playgroud)
所以现在你正在引用UserStatus.Anonymous.GetDescription().
当然,你总是可以创建自己的DatabaseMapAttribute(或者你有什么),并创建自己的扩展方法.然后你可以杀死一个引用System.ComponentModel.完全是你的电话.
您无法覆盖ToString枚举,而是可以创建自己的扩展方法,如:
public static class MyExtensions
{
public static string ToUpperString(this UserStatus userStatus)
{
return userStatus.ToString().ToUpper();// OR .ToUpperInvariant
}
}
Run Code Online (Sandbox Code Playgroud)
然后把它称为:
string str = UserStatus.Anonymous.ToUpperString();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
128 次 |
| 最近记录: |