Admin.Core/src/platform/ZhonTai.Common/Extensions/EnumExtension.cs

(完整代码) 1KB

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;

namespace ZhonTai.Common.Extensions;

public static class EnumExtension
{
    public static string ToDescription(this Enum item)
    {
        string name = item.ToString();
        var desc = item.GetType().GetField(name)?.GetCustomAttribute<DescriptionAttribute>();
        return desc?.Description ?? name;
    }

    public static long ToInt64(this Enum item)
    {
        return Convert.ToInt64(item);
    }

    public static List<Dictionary<string, object>> ToList(this Enum value, bool ignoreNull = false)
    {
        var enumType = value.GetType();

        if (!enumType.IsEnum)
            return null;

        return Enum.GetValues(enumType).Cast<Enum>()
            .Where(m => !ignoreNull || !m.ToString().Equals("Null")).Select(x => new Dictionary<string,object>
            {
                ["Label"] = x.ToDescription(),
                ["Value"] = x
            }).ToList();
    }

    public static List<Dictionary<string, object>> ToList<T>(bool ignoreNull = false)
    {
        var enumType = typeof(T);

        if (!enumType.IsEnum)
            return null;

        return Enum.GetValues(enumType).Cast<Enum>()
             .Where(m => !ignoreNull || !m.ToString().Equals("Null")).Select(x => new Dictionary<string, object>
             {
                 ["Label"] = x.ToDescription(),
                 ["Value"] = x
             }).ToList();
    }
}

24 小时内免费解锁 3 个项目,之后 1 积分/个。 规则说明

AI 解读

登录后可用,每次 10 积分,解读结果公开显示在下面。

还没有人解读过这个文件。