首先,在目前C#版本中并没有一个直接返回枚举的key-value形式的有效方法,可能在C#枚举的设计思想上并不至支持这样使用,但枚举的格式很像键值对是有办法满足这一需求的。
随便定义一个枚举:
public enum En{aaa = 1,bbb = 2,ccc = 3}
返回枚举的key-value格式方法:
public static Dictionary<string, int> GetEnumDic(Type en) {Dictionary<string, int> enumDic = new Dictionary<string, int>();string[] enumKey = Enum.GetNames(en);int[] enumValue = new int[enumKey.Length];Enum.GetValues(en).CopyTo(enumValue, 0);for (int i = 0; i < enumKey.Length; i++){enumDic.Add(enumKey[i], enumValue[i]);}return enumDic;}
调用:
Dictionary<string, int> dic = GetEnumDic1(typeof(En));
如果觉得《C#获取枚举的key-value格式》对你有帮助,请点赞、收藏,并留下你的观点哦!