这个c#方法有什么问题?

bal*_*569 3 c# methods return-value switch-statement

我用这个方法来获取文件扩展名,

public string ReturnExtension(string fileExtension)
    {
        switch (fileExtension)
        {
            case ".doc":
            case ".docx":
                return "application/ms-word";
        }
    }
Run Code Online (Sandbox Code Playgroud)

当我编译它我得到错误BaseClass.ReturnExtension(string)': not all code paths return a value..任何建议......

Jus*_*ner 17

default如果从switch语句内部返回,则需要添加条件.

// As SLaks mentioned, you should be case in-sensitive.
// Therefore, I'm comparing only the Lower Case version of the extensio

switch(fileExtension.ToLowerInvariant())
{
    case ".doc":
    case ".docx":
        return "application/ms-word";
    default:
        // You could also throw an Exception here if unknown extensions
        // are truly invalid (which seems to be the more popular choice)
        //
        // Since it looks like you're returning a content-type for a
        // download, I would default to octet-stream so the user would
        // just get a download window.
        return "application/octet-stream";
}
Run Code Online (Sandbox Code Playgroud)

  • @Adrian:错了.一个empy案例可以隐含地落空. (3认同)

Jam*_*Ide 17

如果fileExtension不是".doc"或".docx",则您尚未指定该方法应返回的内容.您可以通过向switch语句添加默认大小写来完成此操作.假设其他fileExtension值无效,您应该抛出异常:

public string ReturnExtension(string fileExtension)
{
    switch (fileExtension)
    {
        case ".doc":
        case ".docx":
            return "application/ms-word";
        default:
            throw new ArgumentException(string.Format("Invalid fileExtension '{0}'.", fileExtension));
    }
}
Run Code Online (Sandbox Code Playgroud)