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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

  2021-03-18 我要评论
想了解关于c#中枚举类型支持显示中文的扩展说明的相关内容吗,在本文为您仔细讲解c#中枚举类型支持显示中文的扩展的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:枚举类型,中文扩展,下面大家一起来学习吧。

复制代码 代码如下:

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们