代码之家  ›  专栏  ›  技术社区  ›  dylanT

如何获取给定值的常量名称

c#
  •  4
  • dylanT  · 技术社区  · 12 年前

    固件制造商不时会发布一个API,其中包含如下类:

    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
    }
    

    我无法控制这门课,而且很可能会时不时地有一门新课,所以我真的不想重写它。

    在我的代码中,我可以从一个数据文件中访问一个整数,该整数指示文件所来自设备的“制造商”。

    如果可能的话,我希望在我的UI上显示制造商的名称,而不是数字,但我能找到的唯一交叉引用是这个类。

    那么,如果我有文件中的数字“6”,我如何将其转换为文本“Exocomm”?

    4 回复  |  直到 12 年前
        1
  •  6
  •   Amir Popovich    12 年前

    使用反射保持简单:

       var props = typeof(Manufacturer).GetFields(BindingFlags.Public | BindingFlags.Static);
       var wantedProp = props.FirstOrDefault(prop => (ushort)prop.GetValue(null) == 6);
    
        2
  •  2
  •   Rahul Tripathi    12 年前

    您可以这样尝试:

    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;
    }
    

    同时检查 C#: Using Reflection to get constant values

        3
  •  1
  •   Avner Shahar-Kashtan    12 年前

    一个选项可能是编写一个脚本,将该类作为参数,并创建 Enum 班(因此,基本上,将类头更改为enum,在公司名称之前删除垃圾,并更改 ; 到 , 除了最后一个。

    然后,您可以使用具有值的枚举。

        4
  •  0
  •   Avner Shahar-Kashtan    12 年前

    一个好的解决方案是将Amir Popovich和Marcin Juraszek建议的通过代码检索常量值-名称关系的反射选项与Noctis建议的自动构建Enum结合起来。

    如果这不是经常更改的代码(我理解是这样),那么动态构建值名称字典并在运行时访问它比静态创建枚举并将其包含在项目中开销更大。

    将其添加为构建步骤,并将处理时间移动到编译器,而不是运行时。