软件编程
位置:首页>> 软件编程>> C#编程>> 关于c#中枚举类型支持显示中文的扩展说明

关于c#中枚举类型支持显示中文的扩展说明

  发布时间:2023-02-02 22:35:02 

标签:枚举类型,中文扩展


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

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com