欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.net 枚举(使用备注)

程序员文章站 2022-05-13 17:32:18
获取备注的类: ///   /// 备注特性 /// public class RemarkAttribute : Attribute { priv...

获取备注的类:

///

 

/// 备注特性
///

public class RemarkAttribute : Attribute
{
private string m_remark;
public RemarkAttribute(string remark)
{
this.m_remark = remark;
}
///
/// 备注
///

public string Remark
{
get { return m_remark; }
set { m_remark = value; }
}
///
/// 获取枚举的备注信息
///

///枚举值
///
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;
}
}
}
///
/// 枚举扩展类
///

public static class EnumExtension
{
///
/// 获取枚举的备注信息
///

///
///
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
{
///


/// 成功
///

[Remark(成功)]
SUCCESS = 1,
///
/// 失败
///

[Remark(失败)]
FAILED = 0,
///
/// xml格式错误
///

[Remark(xml格式错误)]
XMLFORMATERROR = 2,
///
/// 签名错误
///

[Remark(签名错误)]
SINGERROR = 3,
///
/// 引用了不存在的对象(例如错诨的订单号)
///

[Remark(引用了不存在的对象(例如错诨的订单号))]
ORDERIDERROR = 101,
///
/// 业务状态不正确
///

[Remark(业务状态不正确)]
STATUSERROR = 102,
///
/// 由于业务限制导致业务不能执行
///

[Remark(由于业务限制导致业务不能执行)]
YEWULIMIT = 103,
///
/// 实名认证失败
///

[Remark(实名认证失败)]
IDENTIFICATION = 104
}

 

调用方法:

CodeEmun enumItem = (CodeEmun)Enum.Parse(typeof(InvestmentCommon.CodeEmun), notifyInfo.Code.ToString());
string codeMessage = RemarkAttribute.GetEnumRemark(enumItem);