有没有更好的方法来重构这段代码?

时间:2018-07-25 18:52:58

标签: c#

这只是示例代码。我想知道是否有更好的方法来替换if

public enum FileType
{
    Unknown = 0,
    Text = 1,
    Word = 2,
    Excel = 3,
    Csv = 4
}

private static string GetFormatedFile(string fileName)
{
    var file = FileType.Unknown;

    if (fileName.Contains(".txt"))
    {
         file = FileType.Text;
    }
    else if(fileName.Contains(".doc"))
    {
         file = FileType.Word;
    }
    else if(fileName.Contains(".xlsx"))
    {
          file = FileType.Excel;
    }
    else if (fileName.Contains(".csv"))
    {
           file = FileType.Csv;
    }

    switch (file)
    {
         case FileType.Text: return fileName.Split(".")[3];
         case FileType.Word: return fileName.Split("_")[4];
         case FileType.Excel: return fileName.Split(".")[3];
         case FileType.Csv: return fileName.Split("_")[4];
         default: throw new NotSupportedException($"File Type not ready => {file}");
    }
}

3 个答案:

答案 0 :(得分:1)

您可以在字典中映射扩展名,然后像这样进行查找:

var map = 
    new Dictionary<String, FileType>()
    {
        {".txt", FileType.Text},
        {".doc", FileType.Word},
        {".xlsx", FileType.Excel},
        {".csv", FileType.Csv},
    };

var file = FileType.Unknown;
if (map.TryGetValue(Path.GetExtension(fileName), out var type))
{
    file = type;
}

答案 1 :(得分:0)

您可以完全摆脱enumswitch

private static string GetFormatedFile(string fileName)
{
    var ext = Path.GetExtension(fileName);
    switch (ext)
    {
        case ".txt":
            return fileName.Split(new char[] { '.' })[3]; break;
        case ".doc":
            return fileName.Split(new char[] { '_' })[3]; break;
        default:
            throw new NotSupportedException("$"File Type not ready => {ext}"");
    }
}

答案 2 :(得分:0)

interface IFileNameProvider
{
    string GetFileName(string name);
    bool CanHandle(string name);
} 

class WordCsvFileNameProvider : IFileNameProvider
{
    public string GetFileName(string name){
        return name.Split("_")[4];
    }

    public bool CanHandle(string name){
        return name.Contains(".doc") || name.Contains(".csv");
    }
} 

class TextExcelFileNameProvider : IFileNameProvider
{
    public string GetFileName(string name){
        return name.Split(".")[3];
    }

    public bool CanHandle(string name){
        return name.Contains(".txt") || name.Contains(".xlsx");
    }
} 

您注入提供程序,然后按如下方式使用它们:

private static string GetFormatedFile(string fileName)
{
    var provider = fileNameProviders.FirstOrDefault(fnp => fnp.CanHandle(fileName));

    if(provider == null)
        throw new NotSupportedException($"File Type not ready => {file}");

    return provider.GetFileName(fileName);
}