C#扩展方法:获取枚举Enum的description内容

通过枚举的名称获取分配的Description内容

源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

public static class EnumHelper<T>
{
public static string GetEnumDescription(string value)
{
Type type = typeof(T);
var name = Enum.GetNames(type).Where(f => f.Equals(value, StringComparison.CurrentCultureIgnoreCase)).Select(d => d).FirstOrDefault();

if (name == null)
{
return string.Empty;
}
var field = type.GetField(name);
var customAttribute = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
return customAttribute.Length > 0 ? ((DescriptionAttribute)customAttribute[0]).Description : name;
}
}

示例

1
2
3
4
5
6
7
8
9
10
11
public enum GradeEnum
{
[Description("Passed")]
Pass,
[Description("Failed")]
Failed,
[Description("Promoted")]
Promoted
}

string description = EnumHelper<GradeEnum>.GetEnumDescription("pass");
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×