irc-netcore-api/IRaCIS.Core.Infrastructure/Extention/EnumToSelectExtension.cs

65 lines
2.2 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
namespace IRaCIS.Core.Infrastructure.Extention
{
public static class EnumToSelectExtension
{
/// <summary>
/// 将枚举转换成字典(枚举,自定义描述)
/// </summary>
/// <typeparam name="TEnum"></typeparam>
/// <param name="exceptList">需要排除的枚举</param>
/// <returns></returns>
public static Dictionary<object, string> ToSelect<TEnum>( params TEnum[] exceptList) where TEnum : struct, Enum
{
var type = typeof(TEnum);
var dict = new Dictionary<object, string>();
foreach (var value in Enum.GetValues<TEnum>())
//foreach (var value in type.GetEnumValues())
{
var attr = type.GetField(value.ToString())
.GetCustomAttribute<DescriptionAttribute>();
if (attr is null || exceptList.Contains(value)) continue;
var key = type.GetFields().FirstOrDefault(t=>t.Name== value.ToString()).GetRawConstantValue();
dict[key] = attr.Description;
}
return dict;
}
/// <summary>
/// 扩展方法获得枚举的Description
/// </summary>
/// <param name="value">枚举值</param>
/// <param name="nameInstead">当枚举值没有定义DescriptionAttribute是否使用枚举名代替默认是使用</param>
/// <returns>枚举的Description</returns>
public static string GetDescription(this Enum value, Boolean nameInstead = true)
{
Type type = value.GetType();
string name = Enum.GetName(type, value);
if (name == null)
{
return null;
}
FieldInfo field = type.GetField(name);
DescriptionAttribute attribute = System.Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attribute == null && nameInstead == true)
{
return name;
}
return attribute?.Description;
}
}
}