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

 

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM