關于c#中枚舉類型支持顯示中文的擴展說明
AuditEnum.cs :
public enum AuditEnum
{
Holding=0,
Auditing=1,
Pass=2,
Reject=3
}
以asp.net為例 , 程序中某個方法可能會這樣使用枚舉值?。?BR>public void HandleAudit(int userID, AuditEnum ae)
{
if (ae==AuditEnum.Pass)
{
//do something
}
else if (ae==AuditEnum.Reject)
{
//do other something
}
}
asp.net頁面往往需要顯示中文枚舉信息?。骸 ?/P>
序號
項目
狀態(tài)
審核人
請假單
審核通過
張三
解決方法 : 給枚舉項增加DescriptionAttribute后利用反射來獲取中文信息.
步驟?。?/P>
1?。≡诙x枚舉AuditEnum的類中添加名稱空間System.ComponentModel , 給每個枚舉項加DescriptionAttribute , 示例代碼如下?。?/P>
using System.ComponentModel;
public enum AuditEnum
{
[Description("未送審")]
Holding=0,
[Description("審核中")]
Auditing=1,
[Description("審核通過")]
Pass=2,
[Description("駁回")]
Reject=3
}
2 . 自定義一個類EnumService.cs , 增加靜態(tài)方法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()的調用 , 示例代碼如下?。?/P>
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#中實現(xiàn)輸入漢字獲取其拼音(漢字轉拼音)的2種方法
這篇文章主要介紹了C#中實現(xiàn)輸入漢字獲取其拼音(漢字轉拼音)的2種方法,本文分別給出了使用微軟語言包、手動編碼實現(xiàn)兩種實現(xiàn)方式,需要的朋友可以參考下2015-01-01C#使用FluentHttpClient實現(xiàn)請求WebApi
FluentHttpClient 是一個REST API 異步調用 HTTP 客戶端,調用過程非常便捷,下面我們就來學習一下C#如何使用FluentHttpClient實現(xiàn)請求WebApi吧2023-12-12C#中多態(tài)現(xiàn)象和多態(tài)的實現(xiàn)方法
這篇文章主要介紹了C#中多態(tài)現(xiàn)象和多態(tài)的實現(xiàn)方法,較為詳細的分析了多態(tài)的原理與C#實現(xiàn)多態(tài)的方法,以及相關的注意事項,需要的朋友可以參考下2015-05-05C#使用RenderControl將GridView控件導出到EXCEL的方法
這篇文章主要介紹了C#使用RenderControl將GridView控件導出到EXCEL的方法,是C#應用程序設計中非常實用的一個功能,需要的朋友可以參考下2014-08-08