使用特性代替了直接使用中文作为属性。特意摘抄部分为以后使用方便
/// <summary>/// 枚举帮助类/// </summary>public static class EnumTools {/// <summary>/// 获取当前枚举值的描述和排序/// </summary>/// <param name="value"></param>/// <returns>返回元组Tuple(string,int)</returns>public static Tuple<string,int> GetDescription(this Enum value) {int order = 0;string description = string.Empty; Type type = value.GetType();// 获取枚举FIEldInfo fIEldInfo = type.GetFIEld(value.ToString());// 获取枚举自定义的特性DescriptionAttributeobject[] attrs = fIEldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false); DescriptionAttribute attr = (DescriptionAttribute)attrs.FirstOrDefault(a => a is DescriptionAttribute); description = fIEldInfo.name;if (attr != null) { order = attr.Order; description = attr.name; }return new Tuple<string,int>(description,order); }/// <summary>/// 获取当前枚举的所有描述/// </summary>/// <returns></returns>public static List<keyvaluePair<int, string>> GetAll<T>() {return GetAll(typeof(T)); }/// <summary>/// 获取所有的枚举描述和值/// </summary>/// <param name="type"></param>/// <returns></returns>public static List<keyvaluePair<int, string>> GetAll(Type type) { List<EnumToolsModel> List = new List<EnumToolsModel>();// 循环枚举获取所有的FIEldsforeach (var fIEld in type.GetFIElds()) {// 如果是枚举类型if (fIEld.FIEldType.IsEnum) {object tmp = fIEld.GetValue(null); Enum enumValue = (Enum)tmp;int intValue = Convert.ToInt32(enumValue);var dec = enumValue.GetDescription();int order= dec.Item2;string showname = dec.Item1; // 获取描述和排序List.Add(new EnumToolsModel { Key = intValue, name = showname, Order = order }); } }// 排序并转成keyvalue返回return List.OrderBy(i => i.Order).Select(i => new keyvaluePair<int, string>(i.Key, i.name)).ToList(); }/// <summary>/// 枚举Model/// </summary> partial class EnumToolsModel {public int Order { get; set; }public string name { get; set; }public int Key { get; set; } } }/// <summary>/// 枚举特性/// </summary>[AttributeUsage(AttributeTargets.FIEld, AllowMultiple = false, inherited = false)]public class DescriptionAttribute : Attribute {/// <summary>/// 排序/// </summary>public int Order { get; set; }/// <summary>/// 名称/// </summary>public string name { get; set; }/// <summary>/// 定义描述名称/// </summary>/// <param name="name">名称</param>public DescriptionAttribute(string name) { name = name; }/// <summary>/// 定义描述名称和排序/// </summary>/// <param name="name">名称</param>/// <param name="order">排序</param>public DescriptionAttribute(string name, int order) { name = name; Order = order; } }VIEw Code
把原文中的out参数替换成返回元组,由于项目是vs2015开发,不能用c#7.0特性,否则用7.0中的值元组应该更好一点。性能和显示友好性都会有改进。 总结
以上是内存溢出为你收集整理的Enum扩展特性实例代码全部内容,希望文章能够帮你解决Enum扩展特性实例代码所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)