测试枚举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<T>(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;
}
}
}
C#枚举与描述属性
本文介绍了一种在C#中使用枚举与描述属性的方法,通过自定义扩展方法GetDescription来获取枚举项的描述信息。此方法首先检查传入的对象是否为枚举类型,然后遍历所有枚举值,找到对应描述属性并返回。
329

被折叠的 条评论
为什么被折叠?



