c# 添加中文描述 给enum_关于c#中枚举类型支持显示中文的扩展说明

AuditEnum.cs :

public enum AuditEnum

{

Holding=0,

Auditing=1,

Pass=2,

Reject=3

}

以asp.net为例 , 程序中某个方法可能会这样使用枚举值 :

public void HandleAudit(int userID, AuditEnum ae)

{

if (ae==AuditEnum.Pass)

{

//do something

}

else if (ae==AuditEnum.Reject)

{

//do other something

}

}

asp.net页面往往需要显示中文枚举信息 :

序号

项目

状态

审核人

请假单

审核通过

张三

解决方法 : 给枚举项增加DescriptionAttribute后利用反射来获取中文信息.

步骤 :

1 . 在定义枚举AuditEnum的类中添加名称空间System.ComponentModel , 给每个枚举项加DescriptionAttribute , 示例代码如下 :

using System.ComponentModel;

public enum AuditEnum

{

[Description("未送审")]

Holding=0,

[Description("审核中")]

Auditing=1,

[Description("审核通过")]

Pass=2,

[Description("驳回")]

Reject=3

}

2 . 自定义一个类EnumService.cs , 增加静态方法GetDescription()根据传入的枚举值来读取Description信息 , 示例代码如下 :

public class EnumService

{

public static string GetDescription(Enum obj)

{

string objName = obj.ToString();

Type t = obj.GetType();

FieldInfo fi = t.GetField(objName);

DescriptionAttribute[] arrDesc = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

return arrDesc[0].Description;

}

}

3 . 在输出枚举值的地方增加对EnumService.GetDescription()的调用 , 示例代码如下 :

asp.net页面代码:

//something ui code is here ....

//something ui code is here ....

asp.net页面后台代码:

protected void AuditRepeater_OnItemDataBound(object sender, RepeaterItemEventArgs arg)

{

if (arg.Item.ItemType == ListItemType.Item)

{

Literal audit = arg.Item.FindControl("AuditText") as Literal;

AuditEnum ae = AuditEnum.Pass; //根据项目的实际情况赋值,这里为简化赋值AuditEnum.Pass

audit.Text = EnumService.GetDescription(we);

}

}

全文完 .

以上代码运行于VS2010 , 有任何问题请在下方留言 , 喜欢就点推荐.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值