场景
有时候我们获取的是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