Determine the name of a constant based on the value

后端 未结 7 925
广开言路
广开言路 2021-01-05 22:07

Is there a way of determining the name of a constant from a given value?

For example, given the following:

public const uint ERR_OK = 0x00000000;

Ho

相关标签:
7条回答
  • 2021-01-05 22:28

    The easiest way would be to switch to using an enum

    0 讨论(0)
  • 2021-01-05 22:29

    I don't think you can do that in a deterministic way. What if there are multiple constants with the same value?

    0 讨论(0)
  • 2021-01-05 22:30

    You won't be able to do this since constants are replaced at compilation time with their literal values.

    In other words the compiler takes this:

    class Foo
    {
        uint someField = ERR_OK;
    }
    

    and turns it into this:

    class Foo
    {
        uint someField = 0;
    }
    
    0 讨论(0)
  • 2021-01-05 22:34

    You may be interested in Enums instead, which can be programmatically converted from name to value and vice versa.

    0 讨论(0)
  • 2021-01-05 22:37

    In general, you can't. There could be any number of constants with the same value. If you know the class which declared the constant, you could look for all public static fields and see if there are any with the value 0, but that's all. Then again, that might be good enough for you - is it? If so...

    public string FindConstantName<T>(Type containingType, T value)
    {
        EqualityComparer<T> comparer = EqualityComparer<T>.Default;
    
        foreach (FieldInfo field in containingType.GetFields
                 (BindingFlags.Static | BindingFlags.Public))
        {
            if (field.FieldType == typeof(T) &&
                comparer.Equals(value, (T) field.GetValue(null)))
            {
                return field.Name; // There could be others, of course...
            }
        }
        return null; // Or throw an exception
    }
    
    0 讨论(0)
  • 2021-01-05 22:41

    I may be late.. but i think following could be the answer

    public static class Names
        {
            public const string name1 = "Name 01";
            public const string name2 = "Name 02";
    
            public static string GetNames(string code)
            {
                foreach (var field in typeof(Names).GetFields())
                {
                    if ((string)field.GetValue(null) == code)
                        return field.Name.ToString();
                }
                return "";
            }
        }
    

    and following will print "name1"

    string result = Names.GetNames("Name 01");
    Console.WriteLine(result )
    
    0 讨论(0)
提交回复
热议问题