关于c#中枚举类型支持显示中文的扩展说明_C#教程-查字典教程网
关于c#中枚举类型支持显示中文的扩展说明
关于c#中枚举类型支持显示中文的扩展说明
发布时间:2016-12-28 来源:查字典编辑
摘要:复制代码代码如下:AuditEnum.cs:publicenumAuditEnum{Holding=0,Auditing=1,Pass=2,...

复制代码 代码如下:

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页面代码:

<asp:Repeater ID="AuditRepeater" runat="server" OnItemDataBound="AuditRepeater_OnItemDataBound">

<ItemTemplate>

//something ui code is here ....

<asp:Literal ID="AuditText" runat="server"></asp:Literal>

//something ui code is here ....

</ItemTemplate>

</asp:Repeater>

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 , 有任何问题请在下方留言,喜欢就点推荐.

相关阅读
推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
  • 大家都在看
  • 小编推荐
  • 猜你喜欢
  • 最新C#教程学习
    热门C#教程学习
    编程开发子分类