This article mainly introduces C # from the enumeration values to obtain the corresponding text description of the relevant information, the need for friends can refer to the following
C # Gets the corresponding text description from the enumeration value
Sometimes when the enumeration value is displayed, the text string corresponding to the enumeration value needs to be displayed. One option is to use switch or if at the call to determine the enumeration value and then assign it to a different text string, but this can be cumbersome if more places are used. 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 require this? Is there a more general solution? Some.
You need to use the Description property, assign the attribute to each enumeration value, and then assign the text string that you want to describe in the property. Like what
#region yesnoenum public enum Yesnoenum { [Description ("yes")] Yes, [Description ("no")] No } #endregion
Note: Desscription need to refer to using System.ComponentModel;
So how do you get the value of this description property? We can function the reflection, the code is as follows
public static class Enumutil {#region fetchdescription//<summary>//// to get the description text for the enumeration value // </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: The static method we are writing here can be applied to all enum classes. The enumutil must be a static class, and the method must be a static method, and the first parameter must be this, so that the method can be extended into the Enum class to apply to all enumerations.
Here is the calling code
Yesnoenum yesnoenum = Yesnoenum.yes; String description = Yesnoenum.fetchdescription (); Console.WriteLine (description);
Called the following
You can see that description gets the text of the description that we specified in the enumeration. An enumeration instance of Yesnoenum also adds the extension method fetchdescription.