EnumEx枚举扩展

using System.Reflection;

整数转换为枚举值

int value = 1;
EnumType @enum;
if (Enum.IsDefined(typeof(EnumType), value))
{
    @enum = (EnumType)value;
}

枚举Enum

foreach (EnumType item in Enum.GetValues(typeof(EnumType)))
{
    Console.WriteLine("Name:{0},Value:{1}, Description:{2}", item.ToString(), (int)item, item.GetEnumDescription());
}

自定义特性

/// <summary>
/// 自定义特性
/// </summary>
public class EnumValueAttribute : Attribute
{
    public EnumValueAttribute(string value)
    {
        EnumValue = value;
    }

    /// <summary>
    /// 描述
    /// </summary>
    public string EnumValue { get; set; }
}

获取枚举变量的特性描述

/// <summary>
/// 获取枚举变量的Description
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
public static string GetEnumDescription<T>(this T value) where T : struct
{
    string result = value.ToString();
    Type type = typeof(T);
    FieldInfo info = type.GetField(value.ToString());
    var attributes = info.GetCustomAttributes(typeof(DescriptionAttribute), true);
    if (attributes != null && attributes.FirstOrDefault() != null)
    {
        result = (attributes.First() as DescriptionAttribute).Description;
    }
    return result;
}  

/// <summary>
/// 获取枚举变量的特性描述
/// </summary>
/// <typeparam name="T">枚举类型</typeparam>
/// <param name="value">枚举值</param>
/// <param name="attributeType">特性类型</param>
/// <param name="argumentIndex">特性实例的实参位置</param>
/// <returns></returns>
public static object GetEnumDescription<T>(this T value, Type attributeType, int argumentIndex = 0) where T : struct
{
    Type type = typeof(T);
    FieldInfo info = type.GetField(value.ToString());
    var attribute = info.CustomAttributes.FirstOrDefault(x => x.AttributeType == attributeType);
    if (attribute != null)
    {
        return attribute.ConstructorArguments[argumentIndex].Value;
    }
    return default;
}    

/// <summary>
/// 获取枚举变量的特性描述
/// </summary>
/// <typeparam name="T">枚举类型</typeparam>
/// <param name="value">枚举值</param>
/// <param name="attributeType">特性类型</param>
/// <param name="argumentIndex">特性实例的实参位置</param>
/// <returns></returns>
public object GetEnumDescription<T>(int value, Type attributeType, int argumentIndex = 0) where T : struct
{
    var type = typeof(T);
    if (Enum.IsDefined(type, value))
    {
        var name = Enum.GetName(type, value);
        var @enum = (T)Enum.Parse(type, name);
        return @enum.GetEnumDescription(attributeType);
    }
    return default;
}

var @enum = EnumType.合格;
Console.WriteLine(@enum);
var str = @enum.GetEnumDescription();
Console.WriteLine(str);
var obj = @enum.GetEnumDescription(typeof(DescriptionAttribute));
obj = GetEnumDescription<EnumType>(1,typeof(DescriptionAttribute));

根据Description获取枚举变量

/// <summary>
/// 根据Description获取枚举值
/// </summary>
/// <typeparam name="T">枚举类型</typeparam>
/// <param name="description"></param>
/// <returns></returns>
public static T GetValueByDescription<T>(this string description) where T : struct
{
    Type type = typeof(T);
    foreach (var field in type.GetFields())
    {
        if (field.Name == description)
        {
            return (T)field.GetValue(null);
        }

        var attributes = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), true);
        if (attributes != null && attributes.Any() && attributes.First().Description == description)
        {
            return (T)field.GetValue(null);
        }
    }

    throw new ArgumentException("未能找到对应的枚举!!", description);
}   

/// <summary>
/// 根据自定义属性的值获取枚举值
/// </summary>
/// <typeparam name="T">枚举类型</typeparam>
/// <param name="comment">Enum属性的值</param>
/// <param name="attributeType">对应属性的类型</param>
/// <returns></returns>
public static T GetEnumValueByAttribute<T>(this string comment, Type attributeType) where T : struct
{
    Type type = typeof(T);
    foreach (var field in type.GetFields())
    {
        if (field.Name == comment)
        {
            return (T)field.GetValue(null);
        }
        var attributes = field.GetCustomAttributes(attributeType, true);
        if (attributes != null && attributes.Any())
        {
            var obj = attributes.First();
            var pis = obj.GetType().GetProperties();
            foreach (PropertyInfo pi in pis)
            {
                if (attributeType.Name == pi.Name + "Attribute")
                {
                    var value = pi.GetValue(obj, null).ToString();
                    if (value == comment)
                    {
                        return (T)field.GetValue(null);
                    }
                }
            }
        }
    }
    throw new ArgumentException("未能找到对应的枚举!!", comment);
}  

str = "033";
Console.WriteLine(str);
@enum = str.GetEnumValueByDescription<EnumType>();
Console.WriteLine(@enum);
@enum = str.GetEnumValueByAttribute<EnumType>(typeof(DescriptionAttribute));

根据字符串表示形式获取枚举变量

/// <summary>
/// 根据字符串表示形式获取枚举变量
/// </summary>
/// <typeparam name="T">枚举类型</typeparam>
/// <param name="value">枚举的字符串形式</param>
/// <returns></returns>
public static T GetEnumValue<T>(this string value) where T : struct
{
    T result;
    if (Enum.TryParse(value, true, out result))
    {
        return result;
    }

    throw new ArgumentException("未能找到对应的枚举.", value);
}

@enum = EnumType.不合格;
str = @enum.ToString();
Console.WriteLine(str);
@enum = str.GetEnumValue<EnumType>();
Console.WriteLine(@enum);

Enum变量转List<Source>

/// <summary>
/// Enum变量转List<Source>
/// </summary>
/// <typeparam name="T">Enum类型</typeparam>
/// <returns></returns>
public static List<Source> GetEnumResource<T>() where T : struct
{
    List<Source> rslt = new List<Source>();
    foreach (T item in Enum.GetValues(typeof(T)))
    {
        var displayText = GetEnumDescription(item);
        if (string.IsNullOrEmpty(displayText))
        {
            continue;
        }
        rslt.Add(new Source()
        {
            Key = Convert.ToInt32(item),
            Value = displayText,
        });
    }
    return rslt;
}

/// <summary>
/// Enum枚举转换成List<Source>
/// </summary>
/// <typeparam name="T">枚举类型</typeparam>
/// <param name="attributeType">特性类型</param>
/// <returns></returns>
public static List<Source> EnumToList<T>(Type attributeType) where T : struct
{
    var rslt = new List<Source>();
    foreach (T item in Enum.GetValues(typeof(T)))
    {
        var desc = item.GetEnumDescription(attributeType);
        rslt.Add(new Source
        {
            Key = Convert.ToInt32(item).ToString(),
            Value = desc.ToString(),
        });
    }
    return rslt;
}
/// <summary>
/// Enum转List&lt;enum&gt;
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static List<T> Enum2List<T>() where T : struct
{
    var arr = Enum.GetValues(typeof(T));
    List<T> rslt = new List<T>(arr.Length);
    foreach (T item in arr)
    {
        rslt.Add(item);
    }
    return rslt;
}

var list = EnumExtends.GetEnumResource<EnumType>();
list = EnumToList<EnumType>(typeof(DescriptionAttribute));
foreach (var item in list)
{
Console.WriteLine($"Key:{item.Key}\tDisplayText:{item.Value}");
}

Enum变量转Dictionary<int, string>

/// <summary>
/// Enum枚举转换成Dictionary<int,string>
/// </summary>
/// <typeparam name="T">枚举类型</typeparam>
/// <returns></returns>
public static Dictionary<int, string> EnumToDic<T>() where T : struct
{
	return EnumToDic<T>(typeof(DescriptionAttribute));
}
/// <summary>
/// Enum枚举转换成Dictionary<int,string>
/// </summary>
/// <typeparam name="T">枚举类型</typeparam>
/// <param name="attributeType">特性类型</param>
/// <returns></returns>
public static Dictionary<int, string> EnumToDic<T>(Type attributeType) where T : struct
{
	Dictionary<int, string> rslt = new Dictionary<int, string>();
	foreach (T item in Enum.GetValues(typeof(T)))
	{
		var desc = item.GetEnumDescription(attributeType);
		rslt.Add(Convert.ToInt32(item), desc.ToString());
	}
	return rslt;
}

var list = EnumExtends.EnumToDic<EnumType>();

根据Enum常数值,获取Enum变量名称

@enum = EnumType.不合格;
str = Enum.GetName(typeof(EnumType), (int)@enum);
Console.WriteLine(str);
str = Enum.GetName(typeof(EnumType), @enum);
Console.WriteLine(str);

Source

public enum EnumType
{
    [Description("011")]
    合格 = 1,
    [Description("022")]
    不合格 = 2,
    [Description("033")]
    异常 = 3,
}
// 自定义特性 Description
internal class DescriptionAttribute : Attribute
{
    public DescriptionAttribute(string value)
    {
        Description = value;
    }
    public string Description { get; set; }
}
// 泛型
public class Source<T, K>
{
    /// <summary>
    /// 作为主键用来保存传递的数据
    /// </summary>
    public T Key { get; set; }

    /// <summary>
    /// 作为展示的数据
    /// </summary>
    public K Value { get; set; }

    public override string ToString()
    {
        return Value.ToString();
    }
}
// 默认类型
public class Source : Source<int, string>
{
}
/// <summary>
/// Source 扩展,包含 勾选项
/// </summary>
public class SourceSelected : Source
{
    /// <summary>
    /// true 已选择
    /// </summary>
    public bool IsSelected { get; set; }

    public object Tag { get; set; }
}

.Net Core自带Description特性。

posted @ 2019-12-31 18:07  wesson2019  阅读(147)  评论(0编辑  收藏  举报