新增一个枚举扩展类

/// <summary>
/// 枚举扩展特性
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Enum)]
public class ApiEnum : Attribute
{
  private string _code;

  private string _msg;

  public string Code
  {
    get { return _code; }
    set { _code = value; }
  }

  public string Message
  {
    get { return _msg; }
    set { _msg = value; }
  }
  /// <summary>
  /// 枚举特性
  /// </summary>
  /// <param name="code">消息码</param>
  /// <param name="msg">枚举消息描述</param>
  public ApiEnum(string code,string msg)
  {
    this._code = code;
    this._msg = msg;
  }

  /// <summary>
  /// 获取枚举消息码
  /// </summary>
  /// <param name="obj"></param>
  /// <returns></returns>
  public static string GetCode(Enum obj)
  {
    var fAttrs = GetFieldInfo(obj);
    return fAttrs.Length > 0 ? ((ApiEnum)fAttrs[0]).Code : string.Empty;
  }
  /// <summary>
  /// 获取枚举消息描述
  /// </summary>
  /// <param name="obj"></param>
  /// <returns></returns>
  public static string GetMessage(Enum obj)
  {
    var fAttrs = GetFieldInfo(obj);
    return fAttrs.Length > 0 ? ((ApiEnum)fAttrs[0]).Message : string.Empty;
  }

  private static object[] GetFieldInfo(Enum obj)
  {
    var type = obj.GetType();
    var fieldName = Enum.GetName(type, obj);
    return type.GetField(fieldName).GetCustomAttributes(typeof(ApiEnum), false);
  }

  在枚举中这么使用:

/// <summary>
/// api响应报文枚举
/// </summary>
public enum ApiRespCode
{
    [ApiEnum("000000","response succeed.")]
    S000000,
    [ApiEnum("400000","请求参数验证失败:{0}")]
    F400000,
    [ApiEnum("999999","system error.")]
    E999999
}

  当然,枚举code和message使用英文和中文描述,用户体验会更好。

  获取枚举code或者message的用法:

public ApiException(ApiRespCode apiRespCode) : base(ApiEnum.GetMessage(apiRespCode)) { }
02-12 07:55