【问题标题】:Refactoring if-else statements checking for different file extensions重构检查不同文件扩展名的 if-else 语句
【发布时间】:2013-03-01 04:38:16
【问题描述】:

我有这段代码,我觉得可以清理(我可能是错的),但我想看看是否有人建议我如何将其更改为“更好”

string getExt = Path.GetExtension(DocumentUNCPath.Text);
        var convertFileId = Guid.NewGuid();
        var convertFilePath = @"c:\temp\" + convertFileId + ".pdf";


        if (getExt == ".doc" || getExt == ".docx" || getExt == ".txt" || getExt == ".rtf")
        {
            WordToPdf(convertFilePath);

        }
        else if (getExt == ".xlsx" || getExt == ".xls")
        {
            ExcelToPdf(convertFilePath);
        }
        else if (getExt == ".jpg" || getExt == ".png" || getExt == ".jpeg" || getExt == ".JPG" || getExt == ".PNG")
        {
            ImgToPDF(convertFilePath);
        }

【问题讨论】:

  • 我觉得用它就够了。
  • 至少,getExt = getExt.ToLower() 并从条件中删除多余的张力。

标签: c# asp.net


【解决方案1】:

处理程序的扩展映射是此类情况的标准方法:

// populate with { ".doc", WordToPdf } and similar pairs
Dictionary<string, Action<string> > handlers = ... 


// find and call handler by extension 
// (use TryGetValue to check for existence if needed)
handlers[getExt]( convertFilePath );

【讨论】:

  • 我要补充一点,因为文件名不区分大小写,因此扩展名的比较也不区分大小写。即new Dictionary&lt;string, Action&lt;string&gt;&gt;(StringComparer.OrdinalIgnoreCase)
  • 作为键值的 List&lt;string&gt; 而不是 string 是否更有意义?这是为了防止您希望多个扩展程序执行相同的操作。
  • @gunr2171 不,使用List&lt;string&gt; 作为键是没有意义的,它实际上会破坏使用Dictionary 的目的。使用List&lt;string&gt; 会使查找速度变慢,因为您需要检查每个键,直到找到包含所需扩展名的键,然后在该键处返回该值。
【解决方案2】:

你可以这样做

    switch (getExt.ToUpper()) 
    {    
       case "JPG":    
       case "PNG": 
....

【讨论】:

    【解决方案3】:

    我认为上面的Dictionary&lt;string, Action&lt;string&gt;&gt; 答案是最优雅的答案,但为了完整起见,这里有一个通过字符串扩展的解决方案:

    public static class StringExt
    {
        public static bool MatchesAnyOf(this string text, params string[] targets)
        {
            return targets.Any(target => string.Compare(text, target, StringComparison.OrdinalIgnoreCase) == 0);
        }
    }
    

    然后你可以这样写代码:

    if (getExt.MatchesAnyOf(".doc", ".doxc", ".txt", ".rtf"))
    {
        WordToPdf(convertFilePath);
    }
    else if (getExt.MatchesAnyOf(".xlsx", ".xls"))
    {
        ExcelToPdf(convertFilePath);
    }
    else if (getExt.MatchesAnyOf(".jpg", ".png", ".jpeg", ".JPG", ".PNG")
    {
        ImgToPDF(convertFilePath);
    }
    

    此实现忽略大小写和文化,这适用于文件名,但不适用于一般用途 - 因此实际代码可能必须提供重载来指定文化和比较类型。

    【讨论】:

      【解决方案4】:

      下面的代码最初可能更多,但可以更好地扩展。

      方法之外:

          public static readonly List<string> WorkExtensions = new List<string> { ".doc", ".docx", ".txt", ".trf" };
          public static readonly List<string> ExcelExtensions = new List<string> { ".xlsx", ".xls" };
          public static readonly List<string> ImageExtensions = new List<string> { ".jpg", ".png", ".jpeg" };
      

      方法内部:

          string getExt = Path.GetExtension(DocumentUNCPath.Text);
          var convertFileId = Guid.NewGuid();
          var convertFilePath = @"c:\temp\" + convertFileId + ".pdf";
      
          getExt = getExt.ToLower();
      
          if (WorkExtensions.Contains(getExt))
          {
              WordToPdf(convertFilePath)
          }
          else if (ExcelExtensions.Contains(getExt))
          {
              ExcelToPdf(convertFilePath);
          }
          else if (ImageExtensions.Contains(getExt))
          {
              ImgToPdf(convertFilePath);
          }
      

      【讨论】:

        【解决方案5】:

        如果您正在寻找可扩展性,您可以考虑这样的事情:

        public struct Converter {
          public string         Extension;
          public Action<string> ConvertAction;
        }
        
        public static class Extensions {
          static Action<string> WordToPdf  = (s) => {;};
          static Action<string> ExcelToPdf = (s) => {;};
          static Action<string> ImgToPdf   = (s) => {;};
        
          public static IEnumerable<Converter> Converters = new List<Converter> {
            new Converter {Extension = ".doc",  ConvertAction = WordToPdf},
            new Converter {Extension = ".docx", ConvertAction = WordToPdf},
            new Converter {Extension = ".txt",  ConvertAction = WordToPdf},
            new Converter {Extension = ".rtf",  ConvertAction = WordToPdf},
        
            new Converter {Extension = ".xls",  ConvertAction = ExcelToPdf},
            new Converter {Extension = ".xlsx", ConvertAction = ExcelToPdf},
        
            new Converter {Extension = ".jpg",  ConvertAction = ImgToPdf},
            new Converter {Extension = ".png",  ConvertAction = ImgToPdf},
            new Converter {Extension = ".jpeg", ConvertAction = ImgToPdf},
            new Converter {Extension = ".doc",  ConvertAction = ImgToPdf}
          };
        
          public void RunIt(string extension, string convertFilePath) {
            extension = extension.ToLower();
            var action = ( from a in Converters 
                           where a.Extension.Equals(extension) 
                           select a.ConvertAction).First();
            if (action != null) action(convertFilePath);
          }
        }
        

        【讨论】:

        • 我今天学到了一些新东西。哇!这看起来非常整洁,尽管它比我开始使用的代码要多,但我也会尝试一下。谢谢!
        • 此时代码更多,但添加一些 nore 扩展,您将达到收支平衡点。此外,它是数据驱动的,可以在运行时从外部文本文件加载。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-04-11
        • 1970-01-01
        • 2021-09-05
        • 1970-01-01
        • 1970-01-01
        • 2023-02-06
        • 2011-04-02
        相关资源
        最近更新 更多