Home > Backend Development > C++ > How Can I Give Friendly Names to C# Enums?

How Can I Give Friendly Names to C# Enums?

Mary-Kate Olsen
Release: 2025-01-19 11:26:10
Original
542 people have browsed it

How Can I Give Friendly Names to C# Enums?

Set friendlier names for C# enums

In C# programming, enumerations are used to define a fixed set of values. Enumeration variables can only take the values ​​defined in the enumeration. However, by default, enumeration members are just numerical values, which is not intuitive enough in some cases. So the question is how to give the enumeration a more friendly name.

Solution using Description attribute

To give enumeration members more understandable names, you can use the Description attribute. This allows a descriptive text string to be specified for each enumeration member. This description can then be obtained using an extension method:

<code class="language-csharp">public static string GetDescription(this Enum value)
{
    Type type = value.GetType();
    string name = Enum.GetName(type, value);
    if (name != null)
    {
        FieldInfo field = type.GetField(name);
        if (field != null)
        {
            DescriptionAttribute attr = 
                   Attribute.GetCustomAttribute(field, 
                     typeof(DescriptionAttribute)) as DescriptionAttribute;
            if (attr != null)
            {
                return attr.Description;
            }
        }
    }
    return null; // 或抛出异常,视情况而定
}</code>
Copy after login

How to use it:

<code class="language-csharp">public enum MyEnum
{
    [Description("Foo 的描述")]
    Foo,
    [Description("Bar 的描述")]
    Bar
}

MyEnum x = MyEnum.Foo;
string description = x.GetDescription();</code>
Copy after login

The above is the detailed content of How Can I Give Friendly Names to C# Enums?. 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