An extended note on the support for displaying Chinese for enumeration types in c
- 2020-05-09 19:10:22
- OfStack
AuditEnum.cs :
public enum AuditEnum
{
Holding=0,
Auditing=1,
Pass=2,
Reject=3
}
In order to asp.net For example, a method in a program might use an enumeration value like this:
public void HandleAudit(int userID, AuditEnum ae)
{
if (ae==AuditEnum.Pass)
{
//do something
}
else if (ae==AuditEnum.Reject)
{
//do other something
}
}
asp.net Pages often need to display Chinese enumeration information:
The serial number
project
state
The reviewer
Request for absence
approved
zhang 3
Solution: add DescriptionAttribute to enumeration items and use reflection to get Chinese information.
Steps:
1. Add the namespace System.ComponentModel to the class that defines enumeration AuditEnum and add DescriptionAttribute to each enumeration item. The sample code is as follows:
using System.ComponentModel;
public enum AuditEnum
{
[Description(" Not submitted ")]
Holding=0,
[Description(" In the review ")]
Auditing=1,
[Description(" approved ")]
Pass=2,
[Description(" rejected ")]
Reject=3
}
2. Customize one class EnumService.cs, add the static method GetDescription() to read Description information according to the enum value passed in, the sample code is as follows:
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. Add a call to EnumService.GetDescription () where the enumeration value is output. The sample code is as follows:
asp.net Page code:
<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 Page background code:
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; // Assign values based on the actual situation of the project, which is used to simplify the assignment AuditEnum.Pass
audit.Text = EnumService.GetDescription(we);
}
}
The full text.
The above code runs on VS2010. If you have any questions, please leave a comment below.