using System.ComponentModel;
using System.Linq;
using System.Reflection;
namespace System
{
public static class EnumExtensions
{
/// <summary>
/// Enum에 선언된 <see cref="DescriptionAttribute" />의 값을 반환한다.
/// </summary>
/// <remarks>
/// cf. https://stackoverflow.com/a/479417/3781540
/// </remarks>
public static string GetDescription<T>(this T enumerationValue) where T : struct
{
Type type = enumerationValue.GetType();
if (!type.GetTypeInfo().IsEnum)
{
throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");
}
//Tries to find a DescriptionAttribute for a potential friendly name
//for the enum
MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
if (memberInfo != null && memberInfo.Length > 0)
{
var attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false).ToArray();
if (attrs != null && attrs.Length > 0)
{
//Pull out the description value
return ((DescriptionAttribute)attrs[0]).Description;
}
}
//If we have no description attribute, just return the ToString of the enum
return enumerationValue.ToString();
}
}
}