用于 DbEnum 的 EnumHelper





0/5 (0投票)
一个 EnumHelper 类,可在 DbEnum 中重复使用
引言
编写此助手是为了通过 Web Api 调用提供枚举,以列出枚举/标志值和显示字符串,这些字符串仍然与代码的序号值匹配。 后来,它也被用于收集数据并将枚举值填充到数据库中。
通过在枚举上设置 DisplayAttribute 并设置 Description 属性,此助手将有助于获取“显示字符串”。 如果您想使用人类可读的文本而不是序号键,这将非常有用。
用于 DbEnum & IDbEnum:https://codeproject.org.cn/Reference/1186336/DbEnum
public static class EnumHelper
{
public static IEnumerable<dynamic> GetStruct<TEnum>() where TEnum : struct
{
return (from v in GetPrivateDisplayList<TEnum>()
select new { Id = v, Description = v.ToString() });
}
public static IEnumerable<dynamic> GetDisplayList<TEnum>() where TEnum : struct
{
return (from v in GetPrivateDisplayList<TEnum>()
select new { Id = v, Description = v.GetDisplayString() });
}
public static string GetDisplayString(this Enum source)
{
var da = source.GetDisplayAttribute();
return da != null ? da.Description : source.ToString();
}
private static IEnumerable<Enum> GetPrivateDisplayList<TEnum>() where TEnum : struct
{
var ti = typeof(TEnum).GetTypeInfo();
if (!ti.IsEnum) return null;
return ti.GetEnumValues().Cast<Enum>();
}
private static DisplayAttribute GetDisplayAttribute(this Enum source)
{
var fi = source.GetType().GetTypeInfo().GetField(source.ToString());
return fi.GetCustomAttribute<DisplayAttribute>();
}
}