gpt4 book ai didi

c# - 根据值确定常量的名称

转载 作者:太空狗 更新时间:2023-10-29 22:04:22 24 4
gpt4 key购买 nike

有没有办法根据给定的值确定常量的名称?

例如,给定以下内容:

公共(public)结构 ERR_OK = 0x00000000;

如何获得“ERR_OK”?

我一直在寻找 refection,但似乎找不到任何对我有帮助的东西。

最佳答案

一般来说,你不能。可以有任意数量的具有相同值的常量。如果您知道声明该常量的类,您可以查找所有公共(public)静态字段并查看是否有值为 0 的字段,仅此而已。再一次,这对你来说可能已经足够了——是吗?如果是这样...

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
}

关于c# - 根据值确定常量的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1064213/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com