Home >Backend Development >C++ >Can I Assign Friendly Names to Enum Members in C#?
Can C# enums use friendly names?
As you discovered, C# enumeration members can only have literal names, with underscores as delimiters. However, there is a way to assign a "friendly name" to your enumeration.
Solution: Description attribute
You can use the DescriptionAttribute
attribute to provide a friendlier description for each enumeration member. Here is an extension method that simplifies retrieving descriptions:
<code class="language-csharp">public static string GetDescription(this Enum value) { Type type = value.GetType(); string name = Enum.GetName(type, value); FieldInfo field = type.GetField(name); DescriptionAttribute attr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute; return attr != null ? attr.Description : null; }</code>
Usage:
Apply DescriptionAttribute
to each enum member and provide the desired friendly name:
<code class="language-csharp">public enum MyEnum { [Description("此名称有效")] ThisNameWorks, [Description("此名称无效")] ThisNameDoesntWork, [Description("这个也不行")] NeitherDoesThis }</code>
To retrieve friendly names:
<code class="language-csharp">MyEnum x = MyEnum.ThisNameWorks; string description = x.GetDescription();</code>
The above is the detailed content of Can I Assign Friendly Names to Enum Members in C#?. For more information, please follow other related articles on the PHP Chinese website!