Home > Backend Development > C++ > How to Retrieve an Enum's Description Attribute from its Integer Value in C#?

How to Retrieve an Enum's Description Attribute from its Integer Value in C#?

Patricia Arquette
Release: 2025-01-24 20:31:10
Original
620 people have browsed it

How to Retrieve an Enum's Description Attribute from its Integer Value in C#?

Get an enumeration description in C#according to the value

In C#, the lift can have a associated Description attribute, which provides descriptive text for each enumeration value. Based on the cone search description, you can use the following steps:

    Create an enumeration with the description attribute:
<code class="language-csharp">public enum MyEnum
{
    Name1 = 1,
    [Description("另一个描述")]
    HereIsAnother = 2,
    [Description("最后一个描述")]
    LastOne = 3
}</code>
Copy after login
    Define a function to retrieve the description:
<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>
Copy after login
    Using this function to obtain the description of enumeration value:
<code class="language-csharp">var myEnumDescriptions = from MyEnum n in Enum.GetValues(typeof(MyEnum))
                         select new { ID = (int)n, Name = GetEnumDescription(n) };</code>
Copy after login
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>
Copy after login
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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template