当前位置:首页 > Windows程序 > 正文

C# 枚举转键值对,获取描述等通用方法

2021-03-24 Windows程序

/// <summary> /// 扩展方法,获得枚举的Description /// </summary> /// <param>枚举值</param> /// <param>当枚举值没有定义DescriptionAttribute,是否使用枚举名代替,默认是使用</param> /// <returns>枚举的Description</returns> public static string GetDescription<T>(Object value, String otherDesc = "", Boolean nameInstead = false) { var type = typeof(T); if (!type.IsEnum) { throw new ArgumentException("该对象不是一个枚举类型!"); } string name = Enum.GetName(type, Convert.ToInt32(value)); if (name == null) { return otherDesc; } FieldInfo field = type.GetField(name); DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute; if (attribute == null && nameInstead == true) { return name; } return attribute == null ? otherDesc : attribute.Description; } /// <summary> /// 把枚举转换为键值对集合 /// </summary> /// <param>枚举类型</param> /// <param>获得值得文本</param> /// <returns>以枚举值为key,枚举文本为value的键值对集合</returns> public static Dictionary<Int32, String> EnumToDictionary<T>(EnumAppendItemType appendType = EnumAppendItemType.None) { var enumType = typeof(T); if (!enumType.IsEnum) { throw new ArgumentException("传入的参数必须是枚举类型!", "enumType"); } Dictionary<Int32, String> enumDic = new Dictionary<int, string>(); int appendId = Convert.ToInt16(appendType); if (appendType != EnumAppendItemType.None) { enumDic.Add(-999, GetDescription<EnumAppendItemType>(appendId)); } Array enumValues = Enum.GetValues(enumType); foreach (Enum enumValue in enumValues) { Int32 key = Convert.ToInt32(enumValue); String value = GetDescription<T>(key); enumDic.Add(key, value); } return enumDic; }     public enum EnumAppendItemType    {    None = -999,    [Description("--所有--")]    All = 1,    [Description("--请选择--")]    Select = 2,    }     ///   /// 访问设备    ///    public enum DeviceType    {    [Description("PC")]    PC=1,    [Description("移动端")]    Mobile = 2    }

使用方法:

EnumToDictionary<DeviceType>(EnumAppendItemType.All)

注:枚举名是不能出现空格,()-/等字符

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/66842.html