用Dictionary替换switch case提高维护性

用switch case处理一个很长的判断,例如56个民族01代表汉族,02代表藏族,03代表壮族...,当传入数字想获取民族名称时就得写56个case,当传入民族获取背后的数字时,又得再写56个case,如下所示:
private string GetNationValue(string s)
{
    string result = "5";                      
    switch (s)
    {
        case "01":
            result = "汉族";
            break;
        case "02":
            result = "藏族";
            break;
        case "03":
            result = "壮族";
            break;
        case "04":
            result = "朝鲜族";
            break;
        //这里省略其它......
    }         
    return result;
}
private string GetNationKey(string s)
{
    string result = "5";                      
    switch (s)
    {
        case "汉族":
            result = "01";
            break;
        case "藏族":
            result = "02";
            break;
        case "壮族":
            result = "03";
            break;
        case "朝鲜族":
            result = "04";
            break;
        //这里省略其它......
    }         
    return result;
} 

这么长的代码很丑陋,要修改也不容易,可以通过Dictionary来改进,键和值是成对写在一起的,非常容易维护,改写后代码如下:
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");




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值