枚举特性标记和基本处理类及应用

本文探讨了枚举特性的定义和错误类别的创建,并引用了一篇关于枚举描述的文章,提供了实际应用场景。
摘要由CSDN通过智能技术生成

定义错误类别:

/// <summary>
    /// 错误码枚举
    /// </summary>
    public enum CodeEnum : int
    {
        解析报文出错 = 10000,
        数据包为空 = 10001,
        参数无效 = 10002,
        执行失败 = 10003,
        调用接口校验不成功 = 10004,
        应用内部错误 = 10005
    }
自定义错误类:

using Newtonsoft.Json;
using System;

namespace Business
{
    [JsonObject]
    public class ExceptionBiz : Exception
    {
        public ExceptionBiz(CodeEnum code, string msg)
        {
            Code = code;
            Msg = msg;
            LogManage.Add(StackTrace+ msg);//记录日志
        }
        /// <summary>
        /// 业务信息编码
        /// </summary>
        public CodeEnum Code { get; set; }
        /// <summary>
        /// 业务信息消息
        /// </summary>
        public string Msg { get; set; }
    }
}
public static void Add(string content)
        {

            string logPath = GetApp("LogPath");
            if (logPath == "")
                logPath = @"G:\log\";
            //string dirPath = Directory.GetCurrentDirectory() + logPath;

            if (!Directory.Exists(logPath))
            {
                Directory.CreateDirectory(logPath);
            }
            string fileName = DateTime.Now.ToString("yyyyMMdd")+".txt";
            using (FileStream fs = new System.IO.FileStream(logPath + fileName, System.IO.FileMode.Append))
            {
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")+":"+ content);
                }
            }
        }
核心代码:

using System;
using System.Collections.Generic;
using System.Reflection;

namespace Business
{
    public class EnumHelper
    {
        /// <summary>
        /// 用于缓存枚举值的属性值
        /// </summary>
        private static readonly Dictionary<object, EnumAttribute> enumAttr = new Dictionary<object, EnumAttribute>();

        /// <summary>
        /// 获取枚举值的名称,该名称由EnumAttribute定义
        /// </summary>
        /// <param name="value">枚举值</param>
        /// <returns>枚举值对应的名称</returns>
        public static string GetName(Enum value)
        {
            EnumAttribute ea = GetAttribute(value);
            return ea != null ? ea.Name : "";
        }

        /// <summary>
        /// 获取枚举值的名称,该名称由EnumAttribute定义
        /// </summary>
        /// <param name="value">枚举值</param>
        /// <returns>枚举值对应的名称</returns>
        public static string GetDescription(Enum value)
        {
            EnumAttribute ea = GetAttribute(value);
            return ea != null ? ea.Description : "";
        }

        /// <summary>
        /// 从字符串转换为枚举类型
        /// </summary>
        /// <typeparam name="T">枚举类型</typeparam>
        /// <param name="str">要转为枚举的字符串</param>
        /// <returns>转换结果</returns>
        public static T GetEnum<T>(string str)
        {
            if (string.IsNullOrWhiteSpace(str))
                throw new ExceptionBiz(CodeEnum.解析报文出错, "排序对象解析出错!");

            try
            {
                T pe = (T)Enum.Parse(typeof(T), str);
                return pe;
            }
            catch
            {
                Type type = typeof(T);
                string templete = "枚举类型{0}中没有定义{1}项!";
                string msg = string.Format(templete, type.ToString(), str);

                throw new ExceptionBiz(CodeEnum.解析报文出错, msg);
            }
        }

        /// <summary>
        /// 获取枚举值定义的属性
        /// </summary>
        /// <param name="value">枚举对象</param>
        /// <returns>获取枚举对象的描述属性值</returns>
        private static EnumAttribute GetAttribute(Enum value)
        {
            if (enumAttr.ContainsKey(value))
            {
                EnumAttribute ea = enumAttr[value];
                return ea;
            }
            else
            {
                FieldInfo field = value.GetType().GetField(value.ToString());
                if (field == null) return null;
                EnumAttribute ea = null;
                object[] attributes = field.GetCustomAttributes(typeof(EnumAttribute), true);
                if (attributes != null && attributes.Length > 0)
                {
                    ea = (EnumAttribute)attributes[0];
                }
                enumAttr[value] = ea;
                return ea;
            }
        }
    }

    /// <summary>
    ///描述枚举的属性
    /// </summary>
    [AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
    public class EnumAttribute : Attribute
    {
        private string _name;
        private string _description;

        /// <summary>
        /// 枚举名称
        /// </summary>
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        /// <summary>
        /// 枚举描述
        /// </summary>
        public string Description
        {
            get { return _description; }
            set { _description = value; }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="name">枚举名称</param>
        public EnumAttribute(string name)
        {
            this.Name = name;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="name">枚举名称</param>
        /// <param name="description">枚举描述</param>
        public EnumAttribute(string name, string description)
        {
            this.Name = name;
            this.Description = description;
        }
    }
}

另外可参考老外的一篇文章:A Dictionary for Enum Descriptions http://www.codeproject.com/Articles/761518/A-Dictionary-for-Enum-Descriptions

应用:

ProductEnum pe = EnumHelper.GetEnum<ProductEnum>(v.Name);                   //名称获取枚举对象
string name = EnumHelper.GetName(pe);                                       //获取枚举对象的描述
if (string.IsNullOrWhiteSpace(name))
    throw new ExceptionBiz(CodeEnum.解析报文出错, "排序对象映射出错!");

/// <summary>
/// 商品排序枚举
/// </summary>
public enum ProductEnum 
{ 
    [EnumAttribute("sales")]销量,
    [EnumAttribute("mprice3")]价格,
    [EnumAttribute("comments")]评论,
    [EnumAttribute("id")]最新
}


配合之前一篇排序处理: http://blog.csdn.net/joyhen/article/details/39204473
可以很方便的处理多维度排序

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值