确定一个恒定的基于值的名称名称

2023-09-03 05:58:16 作者:药不能停

有没有确定的常数的名称从给定值的方式吗?

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

例如,给出如下:

公共常量UINT ERR_OK = 00000000;

public const uint ERR_OK = 0x00000000;

一个人怎么能获得ERR_OK?

How could one obtain "ERR_OK"?

我一直在寻找恢复体力,但似乎无法找到任何可以帮助我。

I have been looking at refection but cant seem to find anything that helps me.

推荐答案

在一般情况下,你不能。可以有任何数目的具有相同值的常数。如果您知道哪个宣告不断类,你可以看看所有的公共静态字段,看看是否有任何值为0,但仅此而已。再说,这可能是配不上你 - 是什么呢?如果是这样的...

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
}