工具类
using System;
using System.ComponentModel;
using System.Reflection;
namespace Core.Mortgage.Application.Common
{
/// <summary>
///
/// </summary>
public static class EnumUtils
{
/// <summary>
/// 获取枚举描述
/// </summary>
/// <param name="enum"></param>
/// <returns></returns>
public static string GetDescription(this Enum @enum)
{
Type type = @enum.GetType();
string name = Enum.GetName(type, @enum);
if (string.IsNullOrWhiteSpace(name)) return null;
FieldInfo field = type.GetField(name);
DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attribute == null) return name;
return attribute?.Description;
}
}
}
使用
//获取枚举所有值
var types = Enum.GetValues(typeof(Const.BackupFileType));
foreach (var type in types)
{
var backupFileType = type.ToString();
var backupFiles = new BackupFilesOutput
{
BackupFileTypeCd = backupFileType.ToString(),
//获取枚举描述
BackupFileTypeNm = EnumUtils.GetDescription((Enum)type)
};
}