How can I get the value of an enumeration from its description?

I have an enumeration representing all the system build codes in the system:

public enum EAssemblyUnit { [Description("UCAL1")] eUCAL1, [Description("UCAL1-3CP")] eUCAL13CP, [Description("UCAL40-3CP")] eUCAL403CP, // ... } 

In legacy code in another part of the system, I have objects marked with lines that correspond to descriptions of enums. Given one of these lines, what is the cleanest way to get an enum value? I imagine something like:

 public EAssemblyUnit FromDescription(string AU) { EAssemblyUnit eAU = <value we find with description matching AU> return eAU; } 
+4
source share
3 answers

You will need to iterate over all the static enumeration fields (how they are stored in the reflection), finding the Description attribute for each of them ... when you notice the correct one, get the field value.

For instance:

 public static T GetValue<T>(string description) { foreach (var field in typeof(T).GetFields()) { var descriptions = (DescriptionAttribute[]) field.GetCustomAttributes(typeof(DescriptionAttribute), false); if (descriptions.Any(x => x.Description == description)) { return (T) field.GetValue(null); } } throw new SomeException("Description not found"); } 

(It is common to make it reusable for various transfers.)

Obviously, you want to cache descriptions if you do this even a little often, for example:

 public static class DescriptionDictionary<T> where T : struct { private static readonly Dictionary<string, T> Map = new Dictionary<string, T>(); static DescriptionDictionary() { if (typeof(T).BaseType != typeof(Enum)) { throw new ArgumentException("Must only use with enums"); } // Could do this with a LINQ query, admittedly... foreach (var field in typeof(T).GetFields (BindingFlags.Public | BindingFlags.Static)) { T value = (T) field.GetValue(null); foreach (var description in (DescriptionAttribute[]) field.GetCustomAttributes(typeof(DescriptionAttribute), false)) { // TODO: Decide what to do if a description comes up // more than once Map[description.Description] = value; } } } public static T GetValue(string description) { T ret; if (Map.TryGetValue(description, out ret)) { return ret; } throw new WhateverException("Description not found"); } } 
+8
source
 public EAssemblyUnit FromDescription(string AU) { EAssemblyUnit eAU = Enum.Parse(typeof(EAssemblyUnit), AU, true); return eAU; } 
0
source

You can also use Humanizer . To get a description, you can use:

 EAssemblyUnit.eUCAL1.Humanize(); 

and to return an enumeration from a description that you can use

 "UCAL1".DehumanizeTo<EAssemblyUnit>(); 

Disclaimer: I am the creator of Humanizer.

0
source

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


All Articles