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 =https://www.cnblogs.com/mgp200866130/p/ fieldInfo.GetRawConstantValue();
dicFruitCode.Add(Convert.ToInt32(codeValue), fieldInfo.Name.ToString());
}
foreach(var item in dicFruitCode)
{
Console.WriteLine("FieldName:{0}={1}",item.Value,item.Key);
}
如期,實作了所需要的目的,如圖所示,
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/59614.html
標籤:C#
上一篇:C#執行緒 入門
下一篇:C# 委托與事件有啥區別?
