C#中通过单例模式以及Dictionary实现键值对的映射,通过key获取value
生活随笔
收集整理的這篇文章主要介紹了
C#中通过单例模式以及Dictionary实现键值对的映射,通过key获取value
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
場景
有時候我們獲取的是key,比如獲取的是12345這樣的數字,要實現對應的value比如是中文的狀態的映射。
注:
博客主頁:
https://blog.csdn.net/badao_liumang_qizhi
關注公眾號
霸道的程序猿
獲取編程相關電子書、教程推送與免費下載。
實現
首先新建一個工具類,這里是StepStateHelper,然后設置其單例實現
using System; using System.Collections.Generic; using System.Linq; using System.Text;namespace Badao.Entity.Helper {public class StepStateHelper{#region 單例實現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} }然后定義一個私有的Dicktionary類型的字段,定義好鍵值對的映射關系
??????? private Dictionary<short, string> _dicStepStates = new Dictionary<short, string>(){{ 0x04, "霸道" },{ 0x05, "流氓" },{ 0x06, "氣質" },};鍵值對的內容根據自己的需要去確定
然后再定義一個public的屬性用來對上面字段進行獲取
??????? 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 單例實現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, "氣質" },};#endregion#region 屬性定義public Dictionary<short, string> DicStepStates{get{return _dicStepStates;}}#endregion} }然后就可以在代碼中通過
string StepState = ""; StepStateHelper.Instance.DicStepStates.TryGetValue((short)obj, out StepState);去通過key即obj來獲取value即StepState
總結
以上是生活随笔為你收集整理的C#中通过单例模式以及Dictionary实现键值对的映射,通过key获取value的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#中通过list的GetRange方法
- 下一篇: 用HTML和CSS和JS构建跨平台桌面应