C# Enum枚举类型操作扩展类
使用示例:
using System.ComponentModel; namespace SchoolEnterpriseManageSys.Enum
{
/// <summary>
/// 申报级别
/// </summary>
public enum ReportLevel : int
{
/// <summary>
/// 校
/// </summary>
[Description("校")]
School = ,
/// <summary>
/// 省
/// </summary>
[Description("省")]
Province = ,
/// <summary>
/// 部
/// </summary>
[Description("部")]
Ministry = }
}
获取枚举Description值:EnumExtensions.GetDescription(...)
using System;
using System.ComponentModel.DataAnnotations; namespace SchoolEnterpriseManageSys.Project.Dto
{
public class BeAssociatedProjectDto
{
public Guid Id { get; set; }
/// <summary>
/// 类型
/// </summary>
public Enum.ProjectType Type { get; set; }
public string TypeText
{
get
{
return Utilities.EnumHelper.EnumExtensions.GetDescription(this.Type);
}
}
/// <summary>
/// 类型标识
/// </summary>
public Guid ProjectTypeId { get; set; }
/// <summary>
/// 项目编号
/// </summary>
[StringLength()]
public string Number { get; set; }
/// <summary>
/// 项目名称
/// </summary>
[StringLength()]
public string ProjectName { get; set; }
/// <summary>
/// 关联项目标识
/// </summary>
public Guid? RelateProjectId { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public DateTime CreateTime { get; set; }
}
}
以下是源代码
1、ArrayExtensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace UUT.TeamCenter.Utility.EnumHelper
{
/// <summary>
/// 数组,队列对象的列表类
/// </summary>
public static class ArrayExtensions
{
/// <summary>
/// 扩展 Dictionary 根据Value反向查找Key的方法
/// </summary>
public static T1 Get<T1, T2>(this IEnumerable<KeyValuePair<T1, T2>> list, T2 t2)
{
foreach (KeyValuePair<T1, T2> obj in list)
if (obj.Value.Equals(t2)) return obj.Key;
return default(T1);
} /// <summary>
/// 扩展数组方法 可以在前或者后插入一个对象
/// </summary>
/// <param name="obj">要插入的对象</param>
/// <param name="place">位置 after/before</param>
/// <returns></returns>
public static IEnumerable<T> Inject<T>(this IEnumerable<T> list, T obj, ArrayInjectPlace place = ArrayInjectPlace.Top)
{
T[] list2 = new T[list.Count() + ];
int index = ;
foreach (T t in list)
{
list2[place == ArrayInjectPlace.Bottom ? index : index + ] = t;
}
list2[place == ArrayInjectPlace.Bottom ? list.Count() : ] = obj;
return list2;
} /// <summary>
/// 将数组合并成为一个字符串
/// </summary>
public static string Join<T>(this IEnumerable<T> list, char? c = ',')
{
return list.Join(c.ToString());
} public static string Join<T>(this IEnumerable<T> list, string split)
{
return string.Join(split, list);
}
/// <summary>
/// 按指定条件过滤数组
/// </summary>
/// <param name="ac">默认为过滤重复</param>
public static IEnumerable<T> Filter<T>(this IEnumerable<T> list, ArrayFilterRule filterRule = ArrayFilterRule.NoRepeater)
{
List<T> list2 = new List<T>();
foreach (T t in list)
{
if (!list2.Contains(t)) list2.Add(t);
}
return list2;
}
/// <summary>
/// 合并数组 并且去除重复项
/// </summary>
/// <param name="converter">要比较的字段</param>
public static List<T> Merge<T, TOutput>(this IEnumerable<T> objList, Converter<T, TOutput> converter, params IEnumerable<T>[] objs)
{
List<T> list = objList.ToList();
foreach (var obj in objs)
{
list.AddRange(obj.ToList().FindAll(t => !list.Exists(t1 => converter(t1).Equals(converter(t)))));
}
return list;
} /// <summary>
/// 获取数组的索引项。 如果超出则返回类型的默认值
/// </summary>
public static T GetIndex<T>(this IEnumerable<T> list, int index)
{
if (list == null || index >= list.Count() || index < ) return default(T);
return list.ToArray()[index];
} /// <summary>
/// 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
/// <param name="list"></param>
public static string ToQueryString<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> list)
{
return list.ToList().ConvertAll(t => string.Format("{0}={1}", t.Key, t.Value)).Join("&");
} /// <summary>
/// 除去数组中的空值和指定名称的参数并以字母a到z的顺序排序
/// </summary>
/// <param name="filter">过滤规则 默认做为空判断</param>
public static IEnumerable<KeyValuePair<TKey, TValue>> Filter<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> list, Func<TKey, TValue, bool> filter = null)
{
if (filter == null)
{
filter = (key, value) =>
{
return !string.IsNullOrEmpty(key.ToString()) && value != null;
};
}
foreach (var item in list)
{
if (filter(item.Key, item.Value))
yield return new KeyValuePair<TKey, TValue>(item.Key, item.Value);
}
} /// <summary>
/// 不包含指定的Key
/// </summary>
public static IEnumerable<KeyValuePair<TKey, TValue>> Filter<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> list, params TKey[] filter)
{
return list.Filter((key, value) =>
{
return !string.IsNullOrEmpty(key.ToString()) && value != null && !filter.Contains(key);
});
} /// <summary>
/// 按照Key从小大大拍列
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
/// <param name="list"></param>
public static void Sort<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> list)
{
list = list.ToList().OrderBy(t => t.Key);
} /// <summary>
/// 获取父级的继承树(最多支持32级)
/// 包括自己
/// </summary>
/// <typeparam name="TValue">主键类型</typeparam>
/// <param name="obj">要查找的数组对象</param>
/// <param name="id">当前对象的主键值</param>
/// <param name="value">主键字段</param>
/// <param name="parent">父级字段</param>
/// <returns></returns>
public static List<T> GetParent<T, TValue>(this List<T> obj, TValue id, Func<T, TValue> value, Func<T, TValue> parent)
{
int count = ;
T t = obj.Find(m => value.Invoke(m).Equals(id));
List<T> list = new List<T>();
while (t != null)
{
if (count > ) break;
list.Add(t);
t = obj.Find(m => value.Invoke(m).Equals(parent.Invoke(t)));
count++;
}
return list;
} /// <summary>
/// 获取子集列表(包括自己)
/// </summary>
public static void GetChild<T, TValue>(this List<T> obj, TValue id, Func<T, TValue> value, Func<T, TValue> parent, ref List<T> list)
{
if (list == null) list = new List<T>();
var objT = obj.Find(t => value.Invoke(t).Equals(id));
if (objT != null)
{
list.Add(objT);
foreach (T t in obj.FindAll(m => parent.Invoke(m).Equals(id)))
{
obj.GetChild(value.Invoke(t), value, parent, ref list);
}
}
} /// <summary>
/// 获取树形结构的子集执行方法
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TValue"></typeparam>
/// <param name="obj">当前对象</param>
/// <param name="id">当前父节点</param>
/// <param name="value">获取主键的委托</param>
/// <param name="parent">获取父值的委托</param>
/// <param name="action">委托执行的方法 int 为当前的深度</param>
/// <param name="depth">当前的深度</param>
public static void GetTree<T, TValue>(this List<T> obj, TValue id, Func<T, TValue> value, Func<T, TValue> parent, Action<T, int> action, int depth = )
{
foreach (T t in obj.FindAll(m => parent.Invoke(m).Equals(id)))
{
action.Invoke(t, depth + );
obj.GetTree(value.Invoke(t), value, parent, action, depth + );
}
} }
/// <summary>
/// 数组过滤规则
/// </summary>
public enum ArrayFilterRule
{
/// <summary>
/// 过滤重复
/// </summary>
NoRepeater
} /// <summary>
/// 插入数组的位置
/// </summary>
public enum ArrayInjectPlace
{
/// <summary>
/// 在顶部插入
/// </summary>
Top,
/// <summary>
/// 在尾部追加
/// </summary>
Bottom
}
}
2、EnumExtensions.cs
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks; namespace EnumHelper
{
/// <summary>
/// 枚举扩展
/// </summary>
public static class EnumExtensions
{
private static ConcurrentDictionary<Enum, string> _concurrentDictionary = new ConcurrentDictionary<Enum, string>();
private static ConcurrentDictionary<Type, Dictionary<string, string>> _concurrentDicDictionary = new ConcurrentDictionary<Type, Dictionary<string, string>>();
/// <summary>
/// 锁对象
/// </summary>
private static object objLock = new object(); /// <summary>
/// 获取枚举的描述信息(Descripion)。
/// 支持位域,如果是位域组合值,多个按分隔符组合。
/// </summary>
public static string GetDescription(this Enum @this)
{
return _concurrentDictionary.GetOrAdd(@this, (key) =>
{
var type = key.GetType();
var field = type.GetField(key.ToString());
//如果field为null则应该是组合位域值,
return field == null ? key.GetDescriptions() : GetDescription(field);
});
}
/// <summary>
/// 获取枚举的说明
/// </summary>
/// <param name="split">位枚举的分割符号(仅对位枚举有作用)</param>
public static string GetDescriptions(this Enum em, string split = ",")
{
var names = em.ToString().Split(',');
string[] res = new string[names.Length];
var type = em.GetType();
for (int i = ; i < names.Length; i++)
{
var field = type.GetField(names[i].Trim());
if (field == null) continue;
res[i] = GetDescription(field);
}
return string.Join(split, res);
}
private static string GetDescription(FieldInfo field)
{
var att = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute), false);
return att == null ? field.Name : ((DescriptionAttribute)att).Description;
} /// <summary>
/// 把枚举转换成为列表
/// </summary>
public static List<EnumObject> ToList(this Type type)
{
List<EnumObject> list = new List<EnumObject>();
foreach (object obj in Enum.GetValues(type))
{
list.Add(new EnumObject((Enum)obj));
}
return list;
} /// <summary>
/// 构造UTable枚举json样式 eg.{"Resource":{"value":0,"name":"Resource","text":"自有资源"},"New":{"value":1,"name":"New","text":"业务费用"}}
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static Dictionary<string, EnumModel> GetEnumList(this Type type)
{
Dictionary<string, EnumModel> list = new Dictionary<string, EnumModel>();
foreach (object obj in Enum.GetValues(type))
{
list.Add(((Enum)obj).ToString(), new EnumModel((Enum)obj));
}
return list;
} ///<summary>
/// 获取枚举值+描述
///</summary>
///<param name="enumType">Type,该参数的格式为typeof(需要读的枚举类型)</param>
///<returns>键值对</returns>
public static Dictionary<string, string> GetEnumItemValueDesc(Type enumType)
{
Dictionary<string, string> dic = new Dictionary<string, string>();
Type typeDescription = typeof(DescriptionAttribute);
FieldInfo[] fields = enumType.GetFields();
string strText = string.Empty;
string strValue = string.Empty;
foreach (FieldInfo field in fields)
{
if (field.FieldType.IsEnum)
{
strValue = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)).ToString();
object[] arr = field.GetCustomAttributes(typeDescription, true);
if (arr.Length > )
{
DescriptionAttribute aa = (DescriptionAttribute)arr[];
strText = aa.Description;
}
else
{
strText = field.Name;
}
dic.Add(strValue, strText);
}
} return dic; } /// <summary>
/// 获取枚举类型键值对
/// </summary>
/// <param name="em"></param>
/// <returns></returns>
public static Dictionary<string, string> GetEunItemValueAndDesc(Type em)
{
return _concurrentDicDictionary.GetOrAdd(em, (key) =>
{
var type = key.GetType();
if (_concurrentDicDictionary.ContainsKey(key))
return _concurrentDicDictionary[key];
else
return GetEnumItemValueDesc(em);
});
}
///<summary>
/// 获取枚举项+描述
///</summary>
///<param name="enumType">Type,该参数的格式为typeof(需要读的枚举类型)</param>
///<returns>键值对</returns>
public static Dictionary<string, string> GetEnumItemDesc(Type enumType)
{
Dictionary<string, string> dic = new Dictionary<string, string>();
FieldInfo[] fieldinfos = enumType.GetFields();
foreach (FieldInfo field in fieldinfos)
{
if (field.FieldType.IsEnum)
{
Object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
dic.Add(field.Name, ((DescriptionAttribute)objs[]).Description);
}
}
return dic;
}
/// <summary>
/// 获取枚举项描述信息 例如GetEnumDesc(Days.Sunday)
/// </summary>
/// <param name="en">枚举项 如Days.Sunday</param>
/// <returns></returns>
public static string GetEnumDesc(this Enum en)
{
Type type = en.GetType();
MemberInfo[] memInfo = type.GetMember(en.ToString());
if (memInfo != null && memInfo.Length > )
{
object[] attrs = memInfo[].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs != null && attrs.Length > )
return ((DescriptionAttribute)attrs[]).Description;
}
return en.ToString();
} /// <summary>
/// 将注释转换成枚举值,匹配不上返回Null
/// </summary>
/// <param name="type"></param>
/// <param name="strDescription"></param>
/// <returns></returns>
public static int? GetEnumValByDescription(this Type type, string strDescription)
{
int? enumVal = null;
foreach (object obj in Enum.GetValues(type))
{
Enum nEnum = (Enum)obj;
if (nEnum.GetDescription() == strDescription)
{
enumVal = (int)Convert.ChangeType(nEnum, typeof(int));
}
}
return enumVal;
}
}
}
3、EnumModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace UUT.TeamCenter.Utility.EnumHelper
{
public struct EnumModel
{
public EnumModel(Enum um)
{
this.value = (int)Convert.ChangeType(um, typeof(int));
this.name = um.ToString();
this.text = um.GetDescription();
}
public int value { get; set; }
public string name { get; set; }
public string text { get; set; }
}
}
4、EnumObject.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace UUT.TeamCenter.Utility.EnumHelper
{
/// <summary>
/// 枚举、类型的值
/// </summary>
public struct EnumObject
{
public EnumObject(Enum um, string picture = null)
{
this.ID = (int)Convert.ChangeType(um, typeof(int));
this.Name = um.ToString();
this.Description = um.GetDescription();
this.Picture = picture;
} public EnumObject(int id, string name)
{
this.ID = id;
this.Name = this.Description = name;
this.Picture = null;
} public EnumObject(int id, string name, string description, string picture)
{
this.ID = id;
this.Name = name;
this.Description = description;
this.Picture = picture;
} public int ID; public string Name; public string Description; public string Picture;
}
}
C# Enum枚举类型操作扩展类的更多相关文章
- Python中模拟enum枚举类型的5种方法分享
这篇文章主要介绍了Python中模拟enum枚举类型的5种方法分享,本文直接给出实现代码,需要的朋友可以参考下 以下几种方法来模拟enum:(感觉方法一简单实用) 复制代码代码如下: # way1 ...
- enum枚举类型的定义
enum枚举类型的定义方式与某种用法 #include <iostream> using namespace std; int main() { enum TOT{ zero, one, ...
- Enum枚举类型实战总结,保证有用!
一般在我们开发时如果能使用枚举罗列的,一般都会定义一个枚举类型.将枚举类型作为方法的参数,可以方便的进行调用,给我们带来不少的遍历,当然有时候它还不如直接用一个int类型带来,带来一定灵活性.但只要能 ...
- enum枚举类型的使用
修饰符为public static enum,不用加final,否则提示错误. 枚举类的所有实例必须在枚举类中显式列出(,分隔,; 结尾).列出的实例系统会自动添加 public static fin ...
- Java中的Enum枚举类型总结
废话不多说,直接上代码,该例子来源于:http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html public enum Planet { ...
- Java enum枚举类型
java的枚举类型详解: 简单示例: public enum Color{ RED,BLUE,BLACK,YELLOW,GREEN } 复杂示例(带自定义构造方法与类型) public enum En ...
- enum枚举类型
枚举类型的实例是常量,且它们都用大写字母表示. 简单枚举例子: public enum Spiciness { NOT, MILD, MEDIUM, HOT, FLAMING } public cla ...
- C语言--enum,typedef enum 枚举类型详解
原文:http://z515256164.blog.163.com/blog/static/32443029201192182854300/ 有改动 C语言详解 - 枚举类型 注:以下全部代码的执行环 ...
- C++ enum 枚举类型
1. 枚举类型浅谈 假设我们要设计一个打开文件的函数, 打开文件由三种状态: input, output 和 append. 不使用枚举, 我们可能会写出如下的代码 const int input = ...
随机推荐
- jsp页面错误的全局处理
网上搜索spring mvc项目全局异常处理: 大致可以找到两种方案 : 方案1: ExceptionHandlerResolver . spring 提供了两种默认实现,当然你也可以自己实现.. 方 ...
- Spark学习笔记-GraphX-1
Spark学习笔记-GraphX-1 标签: SparkGraphGraphX图计算 2014-09-29 13:04 2339人阅读 评论(0) 收藏 举报 分类: Spark(8) 版权声明: ...
- 2017/2/11CSS基础
一:html中div: 1.DIV标签应用于 Style Sheet(样式表)方面会更显威力,它最终目的是给设计者另一种组织能力,有 Class.Style.title.ID 等属性. 2.<d ...
- Viewer.js 是一款强大的 jQuery 图像浏览插件。
https://blog.csdn.net/qq_29132907/article/details/80136023 一.效果图 二.代码<!DOCTYPE html><html ...
- 【转】python 修改os环境变量
举一个很简单的例子,如果你发现一个包或者模块,明明是有的,但是会发生这样的错误: >>> from algorithm import *Traceback (most recent ...
- iOS后台唤醒实战:微信收款到账语音提醒技术总结
1.前言 微信为了解决小商户老板们在频繁交易中不方便核对.确认到账的功能痛点,产品MM提出了新版本需要支持收款到账语音提醒功能.本文借此总结了iOS平台上的APP后台唤醒和语音合成.播放等一系列技术开 ...
- WebVTT 及 HTML5 <track> 元素简介
https://dev.opera.com/articles/zh-cn/an-introduction-to-webvtt-and-track/ 简介 网络视频文本轨道,简称为 WebVTT, 是一 ...
- IntelliJ IDEA 2017版 spring-boot2.0.2 自动配置Condition
描述: 编译器修改参数 -Dfile.encoding=GBK -Dstr.encoding=GBK Condition位置: 某一个类或注解存在的时候,装配,否则不装配 相关代码: ...
- keepalive主从上同时出现VIP,且均无法消失
低版本bug 双主架构中,keepalived日志出现: more /var/log/messageOct 9 03:16:22 mysql-dzg-60-148 Keepalived_vrrp[85 ...
- 基于脚本的nodemanager管理器
Step 6: Configure Node Manager on the Managed Servers虚拟机环境: 管理服务器IP:192.168.227.10 AdminServer 受管服务 ...