How to get a persistent name given its meaning

The firmware manufacturer sends the API every time and then contains a class like this:

public static class Manufacturer 
{
  public const ushort FooInc = 1;
  public const ushort BarInc = 2;
  public const ushort BigCompany = 3;
  public const ushort SmallCompany = 4;
  public const ushort Innocom = 5;
  public const ushort Exocomm = 6;
  public const ushort Quarqian = 7;
  // snip... you get the idea
}

      

I have no control over this class and there will probably be a new one from time to time, so I don't want to rewrite it.

In my code, I have access to an integer from a data file that specifies the "Manufacturer" of the device from which the file was retrieved.

I would like to display the manufacturer name in my UI instead of a number if possible, but the only cross reference I can find is the class.

So, given that I have the number "6" from the file, how can I turn that into the text "Exocomm"?

+3


source to share


4 answers


Keep it simple using reflection:



   var props = typeof(Manufacturer).GetFields(BindingFlags.Public | BindingFlags.Static);
   var wantedProp = props.FirstOrDefault(prop => (ushort)prop.GetValue(null) == 6);

      

+5


source


You can try this:

public string FindName<T>(Type type, T value)
{
    EqualityComparer<T> c = EqualityComparer<T>.Default;

    foreach (FieldInfo  f in type.GetFields
             (BindingFlags.Static | BindingFlags.Public))
    {
        if (f.FieldType == typeof(T) &&
            c.Equals(value, (T) f.GetValue(null)))
        {
            return f.Name; 
        }
    }
    return null;
}

      



Also check out C #: Using Reflection to Get Constant Values

+2


source


One option would be to write a script that takes this class as a parameter and creates the class Enum

. (so basically changes the class header to enumeration, discards the crap in front of the company name, and changes ;

to ,

for all but the last one.

Then you can just use that enum with the value you have.

+1


source


A good solution would be to combine the Reflection option, in which Amir Popovich and Marcin Jurashek proposed to restore a persistent value-name relationship using code, and Noctis's proposal is to automatically create an Enum from it.

If this is not commonly used code (which I understand is this), then dynamically building a dictionary of values ​​and accessing it at runtime has more overhead than creating an enum statically and including it in your project.

Add it as a build step and move the processing time to the compiler, not the runtime.

0


source







All Articles