85 lines
2.3 KiB
C#
85 lines
2.3 KiB
C#
![]() |
using System;
|
|||
|
using System.Collections.Generic;
|
|||
|
using System.ComponentModel;
|
|||
|
using System.ComponentModel.DataAnnotations;
|
|||
|
using System.Linq;
|
|||
|
using System.Reflection;
|
|||
|
using System.Text;
|
|||
|
using System.Threading.Tasks;
|
|||
|
|
|||
|
namespace VOL.Model
|
|||
|
{
|
|||
|
public static class EnumExtensions
|
|||
|
{
|
|||
|
// 获取 Display Name
|
|||
|
public static string GetDisplayName(this Enum value)
|
|||
|
{
|
|||
|
if (value == null)
|
|||
|
{
|
|||
|
return "";
|
|||
|
}
|
|||
|
|
|||
|
FieldInfo fi = value.GetType().GetField(value.ToString());
|
|||
|
|
|||
|
if (fi == null)
|
|||
|
{
|
|||
|
return value.ToString();
|
|||
|
}
|
|||
|
|
|||
|
DisplayAttribute attribute = fi.GetCustomAttribute<DisplayAttribute>();
|
|||
|
|
|||
|
if (attribute != null && !string.IsNullOrEmpty(attribute.Name))
|
|||
|
{
|
|||
|
return attribute.Name;
|
|||
|
}
|
|||
|
return value.ToString();
|
|||
|
}
|
|||
|
|
|||
|
public static string GetDisplayDescription(this Enum value)
|
|||
|
{
|
|||
|
if (value == null)
|
|||
|
{
|
|||
|
return "";
|
|||
|
}
|
|||
|
|
|||
|
FieldInfo fi = value.GetType().GetField(value.ToString());
|
|||
|
|
|||
|
if (fi == null)
|
|||
|
{
|
|||
|
return value.ToString();
|
|||
|
}
|
|||
|
|
|||
|
DisplayAttribute attribute = fi.GetCustomAttribute<DisplayAttribute>();
|
|||
|
|
|||
|
if (attribute != null && !string.IsNullOrEmpty(attribute.Description))
|
|||
|
{
|
|||
|
return attribute.Description;
|
|||
|
}
|
|||
|
return "";
|
|||
|
}
|
|||
|
public static string Description(this Enum value)
|
|||
|
{
|
|||
|
if (value == null)
|
|||
|
{
|
|||
|
throw new ArgumentNullException(nameof(value), "Enum value cannot be null");
|
|||
|
}
|
|||
|
|
|||
|
// 获取字段信息
|
|||
|
FieldInfo field = value.GetType().GetField(value.ToString());
|
|||
|
|
|||
|
if (field == null)
|
|||
|
{
|
|||
|
// 如果字段信息为空,返回默认的描述
|
|||
|
return "";
|
|||
|
}
|
|||
|
|
|||
|
// 获取 DescriptionAttribute 特性
|
|||
|
var attributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
|
|||
|
var attribute = attributes.FirstOrDefault() as DescriptionAttribute;
|
|||
|
|
|||
|
// 如果特性为空,返回空字符串
|
|||
|
return attribute?.Description ?? "";
|
|||
|
}
|
|||
|
}
|
|||
|
}
|