How to save string descriptions of enum values?

There are a lot of enumerations in the application I'm working on.

These values ​​are usually selected from the application drop-down lists.

What is the common way to store a string description of these values?

Here is the current problem:

Public Enum MyEnum SomeValue = 1 AnotherValue = 2 ObsoleteValue = 3 YetAnotherValue = 4 End Enum 

The drop-down list should contain the following parameters:

 Some Value Another Value Yet Another Value (Minor Description) 

Not all correspond to the name of the enumeration (a brief description on one example), and not all enumeration values ​​are -current values. Some of them remain only for backward compatibility and display (for example, printouts, not forms).

This leads to the following code situation:

 For index As Integer = 0 To StatusDescriptions.GetUpperBound(0) ' Only display relevant statuses. If Array.IndexOf(CurrentStatuses, index) >= 0 Then .Items.Add(New ExtendedListViewItem(StatusDescriptions(index), index)) End If Next 

It seems that this can be done better, and I'm not sure how to do it.

+4
source share
3 answers

You can use the Description attribute (C # code, but it should translate):

 public enum XmlValidationResult { [Description("Success.")] Success, [Description("Could not load file.")] FileLoadError, [Description("Could not load schema.")] SchemaLoadError, [Description("Form XML did not pass schema validation.")] SchemaError } private string GetEnumDescription(Enum value) { // Get the Description attribute value for the enum value FieldInfo fi = value.GetType().GetField(value.ToString()); DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes( typeof(DescriptionAttribute), false); if (attributes.Length > 0) { return attributes[0].Description; } else { return value.ToString(); } } 

A source

+11
source

The most common way I've seen is to annotate your enums with System.ComponentModel.DescriptionAttribute .

 Public Enum MyEnum <Description("Some Value")> SomeValue = 1 ... 

Then, to get the value, use the extension method (sorry my C #, I will convert it in a minute):

 <System.Runtime.CompilerServices.Extension()> Public Function GetDescription(ByVal value As Enum) As String Dim description As String = String.Empty Dim fi As FieldInfo = value.GetType().GetField(value.ToString()) Dim da = CType(Attribute.GetCustomAttribute(fi,Type.GetType(DescriptionAttribute)), DescriptionAttribute) If da Is Nothing description = value.ToString() Else description = da.Description End If Return description End Function 

What is my best hit when converting it to VB. Treat it like a pseudo code;)

+1
source

Source: https://habr.com/ru/post/1314861/


All Articles