重构代码

一网友需要对所写的代码进行重构,原代码如下:

 /// <summary>
        
/// 检查上传文件类型
        
/// </summary>
        
/// <param name="type">文件类型</param>
        
/// <returns></returns>
        public string strType(string type)
        {
            type = type.ToLower();
            type = type.Substring(type.LastIndexOf("."));
            if ((".swf,.flv,.doc,.docx,.jpg,.xls,.xlsx,.txt,.ppt,.pptx,.pub").Contains(type))
            {
                return type;
            }
            else
            {
                switch (type)
                {
                    //case ".txt"://txt文本文件
                    
//    type = ".rtf";
                    
//    break;
                    case ".wps"://wps文件
                        type = ".doc";
                        break;

                    case ".et"://wps的表格文件
                        type = ".xls";
                        break;

                    case ".pps":
                    case ".dps":
                        type = ".ppt";
                        break;
                }
            }
            return type;
        }
    }

 

Insus.NET试重构了一下,去if...else, 和switch ...case的,简单与明了:

 public string strType(string type)
    {
        Dictionary<stringstring> dict_type = new Dictionary<stringstring>();
        dict_type.Add(".swf""swf");
        dict_type.Add(".flv""flv");
        dict_type.Add(".doc""doc");
        dict_type.Add(".docx""docx");
        dict_type.Add(".jpg""jpg");
        dict_type.Add(".xls""xls");
        dict_type.Add(".xlsx""xlsx");
        dict_type.Add(".txt""txt");
        dict_type.Add(".ppt""ppt");
        dict_type.Add(".pptx""pptx");
        dict_type.Add(".pub""pub");
        dict_type.Add(".wps""doc");
        dict_type.Add(".et""xls");
        dict_type.Add(".pps""ppt");
        dict_type.Add(".dps""ppt");
        //如果以后还在有类型需要判断,请加在这里。


        if (dict_type.ContainsKey(type))
            return dict_type[type].ToString();
        return string.Empty;
    }
}

 

posted @ 2012-09-24 22:07  Insus.NET  阅读(629)  评论(2编辑  收藏  举报