C#读取静态类常量属性和值

原文: C#读取静态类常量属性和值

1.背景
最近项目中有一个需求需要从用户输入的值找到该值随对应的名字,由于其它模块已经定义了一份名字到值的一组常量,所以想借用该定义。
2.实现
实现的思路是采用C#支持的反射。
首先,给出静态类中的常量属性定义示例如下。

public static class FruitCode
{
public const int Apple = 0x00080020;
public const int Banana = 0x00080021;
public const int Orange = 0x00080022;
}

其次,编写提取该静态类常量Name和值的方法,如下所示。

复制代码
Type t = typeof(FruitCode);
FieldInfo[] fis = t.GetFields(); // 注意,这里不能有任何选项,否则将无法获取到const常量
Dictionary<int, string> dicFruitCode = new Dictionary<int, string>();
foreach (var fieldInfo in fis)
{
var codeValue = fieldInfo.GetRawConstantValue();
dicFruitCode.Add(Convert.ToInt32(codeValue), fieldInfo.Name.ToString());
}

foreach(var item in dicFruitCode)
{
Console.WriteLine("FieldName:{0}={1}",item.Value,item.Key); }
复制代码

如期,实现了所需要的目的,如图所示。

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/12549335.html