WMSlite/WmsLite.Api/Common/EnumExtensions.cs
zhougf fa1b286463 Add WmsLite monorepo with JWT auth, tenant context, and project READMEs.
Implement API security baseline (sys_user, JWT, audit fields, transactions,
unique constraints) and Web real login with 401 handling. Document setup
and development workflows in root, WmsLite.Api, and WmsLite.Web README files.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-24 14:17:47 +08:00

44 lines
1.4 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.ComponentModel;
using System.Reflection;
namespace WmsLite.Api.Common;
/// <summary>
/// 枚举与 <see cref="DescriptionAttribute"/> 的辅助扩展,便于返回用户可读文案。
/// </summary>
public static class EnumExtensions
{
/// <summary>
/// 获取枚举值的 Description;未标注时返回 <see cref="Enum.ToString"/>。
/// </summary>
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<DescriptionAttribute>(inherit: false);
return string.IsNullOrWhiteSpace(attr?.Description) ? value.ToString() : attr!.Description;
}
/// <summary>
/// 将整型值解析为枚举后取 Description;无法解析时返回 <paramref name="fallback"/> 或数字字符串。
/// </summary>
public static string GetDescription<TEnum>(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();
}
}