首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

用Dictionary轮换switch case提高维护性

2013-11-03 
用Dictionary替换switch case提高维护性用switch case处理一个很长的判断,例如56个民族01代表汉族,02代表

用Dictionary替换switch case提高维护性
用switch case处理一个很长的判断,例如56个民族01代表汉族,02代表藏族,03代表壮族...,当传入数字想获取民族名称时就得写56个case,当传入民族获取背后的数字时,又得再写56个case,如下所示:

public enum FormatType{    GetKey,    GetValue}public class Format{    private static string Get(Dictionary<string, string> dict, FormatType formatType, string code)    {                   if (formatType == FormatType.GetKey)             return dict.FirstOrDefault(d => d.Value == code).Key;        else             return dict.FirstOrDefault(d => d.Key == code).Value;      }    public static string GetNation(FormatType formatType, string code)    {       Dictionary<string, string> dict = new Dictionary<string, string>{                  {"01","汉族"},                {"02","藏族"},                {"03","壮族"},                {"04","朝鲜族"}                //这里省略其它......        };       return Get(dict, formatType, code);   }}
使用:
获取"汉族"的编码
string key = Format.GetNation(FormatType.GetKey, "汉族");
获取"01"代表的民族
string value = Format.GetNation(FormatType.GetValue, "01");




热点排行