由于对英语的天生缺陷,在枚举时一直使用中文,这样就不用看注释就知道枚举意思,今天看到博文
使用特性代替了直接使用中文作为属性。特意摘抄部分为以后使用方便
////// 枚举帮助类/// public static class EnumTools {////// 获取当前枚举值的描述和排序/// /// /// 返回元组Tuple(string,int)public static Tuple 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(description,order); }////// 获取当前枚举的所有描述/// /// public static List<KeyValuePair> GetAll() {return GetAll(typeof(T)); }////// 获取所有的枚举描述和值/// /// /// public static List<KeyValuePair> GetAll(Type type) { List list = new List();// 循环枚举获取所有的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(i.Key, i.Name)).ToList(); }////// 枚举Model/// partial class EnumToolsModel {public int Order { get; set; }public string Name { get; set; }public int Key { get; set; } } }////// 枚举特性/// [AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = false)]public class DescriptionAttribute : Attribute {////// 排序/// public int Order { get; set; }////// 名称/// public string Name { get; set; }////// 定义描述名称/// /// 名称public DescriptionAttribute(string name) { Name = name; }////// 定义描述名称和排序/// /// 名称/// 排序public DescriptionAttribute(string name, int order) { Name = name; Order = order; } }
登录后复制View Code
把原文中的out参数替换成返回元组,由于项目是vs2015开发,不能用c#7.0特性,否则用7.0中的值元组应该更好一点。性能和显示友好性都会有改进。
以上就是Enum扩展特性实例代码的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2439755.html