Home > Backend Development > C++ > How Can I Use Friendly Names with Flexible Enum Values in C#?

How Can I Use Friendly Names with Flexible Enum Values in C#?

Patricia Arquette
Release: 2025-01-19 11:07:10
Original
420 people have browsed it

How Can I Use Friendly Names with Flexible Enum Values in C#?

Tips for using friendly names and flexible enum values ​​in C#

Enumeration types often need to be given more meaningful names to improve code readability and understandability. However, traditional enumeration usage has some limitations in this regard.

For example:

<code class="language-c#">public enum myEnum
{
    ThisNameWorks,
    This Name doesn'tWork,
    Neither.does.this;
}</code>
Copy after login

"ThisNameWorks" is an acceptable enum value, but other values ​​have issues due to containing spaces and special characters. At this time, the "Description" attribute comes in handy.

Description attribute

The

Description attribute allows you to specify a "friendly name" for each enumeration value, which can then be retrieved using an extension method (shown below):

<code class="language-c#">public static string GetDescription(this Enum value)
{
    // 此处省略具体实现
}</code>
Copy after login

Examples of usage

With this extension method you can define enums with user-friendly descriptions:

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

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

This approach allows you to create enumerations that have both machine-readable values ​​and human-readable descriptions, improving code maintainability and user experience.

The above is the detailed content of How Can I Use Friendly Names with Flexible Enum Values 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