A firmware manufacturer is shipping an API every now and then that 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 is likely to be a new one from time to time, so I don't really want to rewrite it.
In my code I have access to an integer from a data file that indicates the "Manufacturer" of the device that the file came from.
I'd like, if possible, to display the name of the manufacturer on my UI, instead of the number, but the only cross reference I can find is this class.
So, given I have the number "6" from the file, how can I turn that into the text "Exocomm"?
Keep it simple using reflection:
var props = typeof(Manufacturer).GetFields(BindingFlags.Public | BindingFlags.Static);
var wantedProp = props.FirstOrDefault(prop => (ushort)prop.GetValue(null) == 6);
You may try like 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 C#: Using Reflection to get constant values
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With