获取备注的类:
/// <summary>
/// 备注特性
/// </summary>
public class RemarkAttribute : Attribute
{
private string m_remark;
public RemarkAttribute(string remark)
{
this.m_remark = remark;
}
/// <summary>
/// 备注
/// </summary>
public string Remark
{
get { return m_remark; }
set { m_remark = value; }
}
/// <summary>
/// 获取枚举的备注信息
/// </summary>
/// <param name="val">枚举值</param>
/// <returns></returns>
public static string GetEnumRemark(Enum val)
{
try
{
Type type = val.GetType();
FieldInfo fd = type.GetField(val.ToString());
if (fd == null)
return string.Empty;
object[] attrs = fd.GetCustomAttributes(typeof(RemarkAttribute), false);
string name = string.Empty;
foreach (RemarkAttribute attr in attrs)
{
name = attr.Remark;
}
return name;
}
catch (Exception ex)
{
Log4NetHelper.Log.Error("GetEnumRemark Erro",ex);
return null;
}
}
}
/// <summary>
/// 枚举扩展类
/// </summary>
public static class EnumExtension
{
/// <summary>
/// 获取枚举的备注信息
/// </summary>
/// <param name="em"></param>
/// <returns></returns>
public static string GetRemark(this Enum em)
{
try
{
Type type = em.GetType();
FieldInfo fd = type.GetField(em.ToString());
if (fd == null)
return string.Empty;
object[] attrs = fd.GetCustomAttributes(typeof(RemarkAttribute), false);
string name = string.Empty;
foreach (RemarkAttribute attr in attrs)
{
name = attr.Remark;
}
return name;
}
catch (Exception ex)
{
Log4NetHelper.Log.Error("GetRemark Error", ex);
return null;
}
}
枚举类:
public enum CodeEmun
{
/// <summary>
/// 成功
/// </summary>
[Remark("成功")]
SUCCESS = 1,
/// <summary>
/// 失败
/// </summary>
[Remark("失败")]
FAILED = 0,
/// <summary>
/// xml格式错误
/// </summary>
[Remark("xml格式错误")]
XMLFORMATERROR = 2,
/// <summary>
/// 签名错误
/// </summary>
[Remark("签名错误")]
SINGERROR = 3,
/// <summary>
/// 引用了不存在的对象(例如错诨的订单号)
/// </summary>
[Remark("引用了不存在的对象(例如错诨的订单号)")]
ORDERIDERROR = 101,
/// <summary>
/// 业务状态不正确
/// </summary>
[Remark("业务状态不正确")]
STATUSERROR = 102,
/// <summary>
/// 由于业务限制导致业务不能执行
/// </summary>
[Remark("由于业务限制导致业务不能执行")]
YEWULIMIT = 103,
/// <summary>
/// 实名认证失败
/// </summary>
[Remark("实名认证失败")]
IDENTIFICATION = 104
}
调用方法:
CodeEmun enumItem = (CodeEmun)Enum.Parse(typeof(InvestmentCommon.CodeEmun), notifyInfo.Code.ToString());
string codeMessage = RemarkAttribute.GetEnumRemark(enumItem);
版权声明:本文为博主原创文章,未经博主允许不得转载。