1.背景
最近項目中有一個需求須要從用戶輸入的值找到該值隨對應的名字,因爲其它模塊已經定義了一份名字到值的一組常量,因此想借用該定義。
2.實現
實現的思路是採用C#支持的反射。
首先,給出靜態類中的常量屬性定義示例以下。ui
public static class FruitCode
{
public const int Apple = 0x00080020; public const int Banana = 0x00080021; public const int Orange = 0x00080022; }
其次,編寫提取該靜態類常量Name和值的方法,以下所示。spa
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); }
如期,實現了所須要的目的,如圖所示。code