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.
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>
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>
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!