C#中通过单例模式以及Dictionary实现键值对的映射,通过key获取value
生活随笔
收集整理的這篇文章主要介紹了
C#中通过单例模式以及Dictionary实现键值对的映射,通过key获取value
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
場(chǎng)景
有時(shí)候我們獲取的是key,比如獲取的是12345這樣的數(shù)字,要實(shí)現(xiàn)對(duì)應(yīng)的value比如是中文的狀態(tài)的映射。
注:
博客主頁(yè):
https://blog.csdn.net/badao_liumang_qizhi
關(guān)注公眾號(hào)
霸道的程序猿
獲取編程相關(guān)電子書、教程推送與免費(fèi)下載。
實(shí)現(xiàn)
首先新建一個(gè)工具類,這里是StepStateHelper,然后設(shè)置其單例實(shí)現(xiàn)
using System; using System.Collections.Generic; using System.Linq; using System.Text;namespace Badao.Entity.Helper {public class StepStateHelper{#region 單例實(shí)現(xiàn)private static string _lockFlag = "StepStateHelperLock";private static StepStateHelper _instance;private StepStateHelper(){}public static StepStateHelper Instance{get{lock(_lockFlag){if (_instance == null){_instance = new StepStateHelper();}return _instance;}}}#endregion} }然后定義一個(gè)私有的Dicktionary類型的字段,定義好鍵值對(duì)的映射關(guān)系
??????? private Dictionary<short, string> _dicStepStates = new Dictionary<short, string>(){{ 0x04, "霸道" },{ 0x05, "流氓" },{ 0x06, "氣質(zhì)" },};鍵值對(duì)的內(nèi)容根據(jù)自己的需要去確定
然后再定義一個(gè)public的屬性用來(lái)對(duì)上面字段進(jìn)行獲取
??????? public Dictionary<short, string> DicStepStates{get{return _dicStepStates;}}完整示例代碼
using System; using System.Collections.Generic; using System.Linq; using System.Text;namespace Badao.Entity.Helper {public class StepStateHelper{#region 單例實(shí)現(xiàn)private static string _lockFlag = "StepStateHelperLock";private static StepStateHelper _instance;private StepStateHelper(){}public static StepStateHelper Instance{get{lock(_lockFlag){if (_instance == null){_instance = new StepStateHelper();}return _instance;}}}#endregion#region 字段定義private Dictionary<short, string> _dicStepStates = new Dictionary<short, string>(){{ 0x04, "霸道" },{ 0x05, "流氓" },{ 0x06, "氣質(zhì)" },};#endregion#region 屬性定義public Dictionary<short, string> DicStepStates{get{return _dicStepStates;}}#endregion} }然后就可以在代碼中通過(guò)
string StepState = ""; StepStateHelper.Instance.DicStepStates.TryGetValue((short)obj, out StepState);去通過(guò)key即obj來(lái)獲取value即StepState
總結(jié)
以上是生活随笔為你收集整理的C#中通过单例模式以及Dictionary实现键值对的映射,通过key获取value的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: C#中通过list的GetRange方法
- 下一篇: C#中格式化小数位数为指定位数的工具类