This article mainly introduces C# related information on obtaining the corresponding text description from the enumeration value. Friends in need can refer to
C# From the enumeration value Detailed explanation of obtaining the corresponding text description
Sometimes when the enumeration value is displayed, it is necessary to display the text string corresponding to the enumeration value. One solution is to use switch or if at the place of call to determine the enumeration value, and then assign it to different text strings, but in this way, if it is used in many places, it will kind of hard. Of course, some people say that in this case, you can encapsulate a method for this enumeration value and then call it. What if there are multiple enumeration types that have such a requirement? Is there any more general solution? some.
You need to use the Description attribute here, assign this attribute to each enumeration value, and then assign the text string to be described in this attribute. For example
#region YesNoEnum public enum YesNoEnum { [Description("是")] Yes, [Description("否")] No } #endregion
Note: Description needs to reference using System.ComponentModel;
How to get the value of this Description attribute? We can use reflection, the code is as follows
public static class EnumUtil { #region FetchDescription /// <summary> /// 获取枚举值的描述文本 /// </summary> /// <param name="value"></param> /// <returns></returns> public static string FetchDescription(this Enum value) { FieldInfo fi = value.GetType().GetField(value.ToString()); DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes( typeof(DescriptionAttribute), false); return (attributes.Length > 0) ? attributes[0].Description : value.ToString(); } #endregion }
Note: Although what we write here is a static method, it can be applied to all Enum classes. EnumUtil must be a static class, and the method must also be a static method, and the first parameter must be this, so that the method can be extended to the Enum class to apply to all enumerations.
The following is the calling code
YesNoEnum yesNoEnum = YesNoEnum.Yes; string description = yesNoEnum.FetchDescription(); Console.WriteLine(description);
The screenshot of the call is as follows
The above is the detailed content of C# Detailed explanation of graphic code to obtain corresponding text from enumeration value. For more information, please follow other related articles on the PHP Chinese website!