C# EnumHelper枚举帮助类
C# 全选
/// <summary>
/// 枚举类型帮助类
/// </summary>
public class EnumHelper
{
/// <summary>
/// 获取枚举类型指定字段的特性(Attribute)
/// </summary>
/// <typeparam name="T">特性(Attribute)类型</typeparam>
/// <param name="enumType">枚举类型</param>
/// <param name="fieldName">字段名称</param>
/// <returns></returns>
public static T GetEnumFieldAttribute<T>(Type enumType, string fieldName) where T : Attribute
{
if (Enum.IsDefined(enumType, fieldName))
{
var field = enumType.GetField(fieldName, BindingFlags.Static | BindingFlags.Public);
return field.GetCustomAttribute<T>();
}
else
{
return default(T);
}
}
/// <summary>
/// 获取枚举的特性
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="enumType"></param>
/// <returns></returns>
public static List<T> GetEnumFieldsAttributes<T>(Type enumType) where T : Attribute
{
var fields = enumType.GetFields(BindingFlags.Static | BindingFlags.Public);
return fields.Select(s => s.GetCustomAttribute<T>()).ToList();
}
/// <summary>
/// 根据 DescriptionAttribute 的描述获取枚举项名称
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="description">描述</param>
/// <returns></returns>
public static string GetFieldByAttributeDescription<T>(string description) where T : Enum
{
var enumType = typeof(T);
var fields = enumType.GetFields(BindingFlags.Static | BindingFlags.Public);
var field = fields.Where(s => s.GetCustomAttribute<DescriptionAttribute>()?.Description == description).FirstOrDefault();
if (field != null)
return field.Name.ToString();
else
return default(T).ToString();
}
/// <summary>
/// 根据 DefaultValueAttribute 的值取枚举项
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">值</param>
/// <returns></returns>
public static T GetFieldByAttributeDefaultValue<T>(string value) where T : struct
{
var enumType = typeof(T);
var fields = enumType.GetFields(BindingFlags.Static | BindingFlags.Public);
var field = fields.Where(s => s.GetCustomAttribute<DefaultValueAttribute>()?.Value.ToString().ToLower() == value.ToLower()).FirstOrDefault();
if (field != null)
{
var fieldName = field.Name.ToString();
T defaultValue = default(T);
if (Enum.TryParse<T>(fieldName, out defaultValue))
return defaultValue;
else
return default(T);
}
else
return default(T);
}
/// <summary>
/// 获取枚举所有项
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static List<String> GetFields<T>()
{
var fields = typeof(T).GetFields(BindingFlags.Static | BindingFlags.Public);
return fields.Select(s => s.Name).ToList();
}
}
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
NewDoc C/S框架网