Determine the name of a constant based on the value

后端 未结 7 1081
广开言路
广开言路 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: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(Type containingType, T value)
    {
        EqualityComparer comparer = EqualityComparer.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
    }
    

提交回复
热议问题