using System; using System.ComponentModel; using System.Reflection; namespace WmsLite.Api.Common; /// /// 枚举与 的辅助扩展,便于返回用户可读文案。 /// public static class EnumExtensions { /// /// 获取枚举值的 Description;未标注时返回 。 /// public static string GetDescription(this Enum value) { ArgumentNullException.ThrowIfNull(value); var field = value.GetType().GetField(value.ToString()); if (field is null) { return value.ToString(); } var attr = field.GetCustomAttribute(inherit: false); return string.IsNullOrWhiteSpace(attr?.Description) ? value.ToString() : attr!.Description; } /// /// 将整型值解析为枚举后取 Description;无法解析时返回 或数字字符串。 /// public static string GetDescription(int value, string? fallback = null) where TEnum : struct, Enum { if (!Enum.IsDefined(typeof(TEnum), value)) { return fallback ?? value.ToString(); } var e = Enum.ToObject(typeof(TEnum), value); return e is Enum en ? en.GetDescription() : value.ToString(); } }