Home >Backend Development >C++ >How to Retrieve an Enum's Description Attribute from its Integer Value in C#?
<code class="language-csharp">public enum MyEnum { Name1 = 1, [Description("另一个描述")] HereIsAnother = 2, [Description("最后一个描述")] LastOne = 3 }</code>
<code class="language-csharp">public static string GetEnumDescription(Enum value) { FieldInfo fi = value.GetType().GetField(value.ToString()); DescriptionAttribute[] attributes = fi.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[]; if (attributes != null && attributes.Length > 0) { return attributes[0].Description; } return value.ToString(); }</code>
<code class="language-csharp">var myEnumDescriptions = from MyEnum n in Enum.GetValues(typeof(MyEnum)) select new { ID = (int)n, Name = GetEnumDescription(n) };</code>Now, you need to retrieve the description of the value according to its integer value, you can:
<code class="language-csharp">int value = 1; string description = GetEnumDescription((MyEnum)value);</code>This will convert the integer value into an enumeration type and pass it to the GetenumDescript function, which will return the corresponding description.
This Revised Response Maintains The Original Image and ITS Formatting, While rewarding the text for Improved Clarity and Flow. ANGED, ENSURING FUNCTIONAL Accuracy. The Language Use is Slightly More Concise and Avoids Unnecessary Repetition.
The above is the detailed content of How to Retrieve an Enum's Description Attribute from its Integer Value in C#?. For more information, please follow other related articles on the PHP Chinese website!