重构if-else语句检查不同的文件扩展名

时间:2013-02-28 19:47:02

标签: c# asp.net

我有这段代码,我觉得可以清理(我可能是错的)但我想知道是否有人有一个建议我怎么能改变这个“更好”

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);
        }

5 个答案:

答案 0 :(得分:15)

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

// 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 );

答案 1 :(得分:4)

你可以做这样的事情

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

答案 2 :(得分:2)

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

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);
}

此实现忽略了适用于文件名的案例和文化,但不适合一般用途 - 因此真正的代码可能必须提供指定文化和比较类型的重载。

答案 3 :(得分:1)

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

方法之外:

    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);
    }

答案 4 :(得分:1)

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

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);
  }
}