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