-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
EnumHelper.cs
46 lines (38 loc) · 1.24 KB
/
EnumHelper.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace SimplCommerce.Infrastructure.Helpers
{
public static class EnumHelper
{
public static IDictionary<Enum, string> ToDictionary(Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
var dics = new Dictionary<Enum, string>();
var enumValues = Enum.GetValues(type);
foreach (Enum value in enumValues)
{
dics.Add(value, GetDisplayName(value));
}
return dics;
}
public static string GetDisplayName(this Enum value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
var displayName = value.ToString();
var fieldInfo = value.GetType().GetField(displayName);
var attributes = (DisplayAttribute[])fieldInfo.GetCustomAttributes(typeof(DisplayAttribute), false);
if (attributes.Length > 0)
{
displayName = attributes[0].Description;
}
return displayName;
}
}
}