Skip to content

Instantly share code, notes, and snippets.

@rqx110
Created September 6, 2018 01:40
Show Gist options
  • Save rqx110/0dc45b5d25f0e17f509d955a112a57cc to your computer and use it in GitHub Desktop.
Save rqx110/0dc45b5d25f0e17f509d955a112a57cc to your computer and use it in GitHub Desktop.
获取Enum描述属性值
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using Abp.Application.Services.Dto;
namespace Abp.Extensions
{
public static class EnumExtensions
{
public static string GetDescription(object e)
{
//获取枚举的Type类型对象
var type = e.GetType();
//获取枚举的所有字段
var fields = type.GetFields();
//遍历所有枚举的所有字段
foreach (var field in fields)
{
if (field.Name != e.ToString())
{
continue;
}
//第二个参数true表示查找EnumDisplayNameAttribute的继承链
if (field.IsDefined(typeof(DescriptionAttribute), true))
{
var attr = field.GetCustomAttribute(typeof(DescriptionAttribute), false) as DescriptionAttribute;
if (attr != null)
{
return attr.Description;
}
}
}
//如果没有找到自定义属性,直接返回属性项的名称
return e.ToString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment