C#Enum拡張メソッドのコードについて
1489 ワード
テスト列挙Enumコード:
Enum拡張コードは次のとおりです.
public enum TestEnum
{
[Description("Unknow")]
Unknown = 0
}
Enum拡張コードは次のとおりです.
using System;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
namespace NetCoreDemo.Common.Extensions
{
public static class StringEnumExtension
{
public static string GetDescription(this T e) where T : IConvertible
{
string desc = string.Empty;
if (e is Enum)
{
Type type = e.GetType();
Array values = Enum.GetValues(type);
foreach (int val in values)
{
if (val == e.ToInt32(CultureInfo.InvariantCulture))
{
MemberInfo[] memInfo = type.GetMember(type.GetEnumName(val));
object[] descriptionAttributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (descriptionAttributes.Length > 0)
{
// we're only getting the first description we find
// others will be ignored
desc = ((DescriptionAttribute)descriptionAttributes[0]).Description;
}
break;
}
}
}
return desc;
}
}
}