我可以/应该在 C# 中替换这个 GOTO 语句吗

Rm5*_*558 4 c# readability goto try-catch

在这里使用 goto 似乎很自然

一个项目需要读取pdf文件,pdf文件可以是以下之一。

  • 不受保护
  • 密码保护1
  • 受密码2保护
  • 密码保护3

只有使用正确的密码才能访问文件,无法预先知道文件需要哪个密码。我们必须尝试所有情况,(包括没有密码)。如果以上密码均无效,则抛出异常。

PdfReader GetPdfReader(string filePath)
{
    PdfReader r = null;
    int Retries = 0;
    start: try
    {
        switch (Retries)
        {
            case 0: r = new PdfReader(filePath); break;
            case 1: r = new PdfReader(filePath, password1); break;
            case 2: r = new PdfReader(filePath, password2); break;
            case 3: r = new PdfReader(filePath, password3); break;
        }
    }
    catch (BadPasswordException ex)
    {
        if (Retries == 3) throw ex;
        Retries++;
        goto start;
    }
    return r;
}
Run Code Online (Sandbox Code Playgroud)

嵌入 try/catch 正在工作,但看起来很难看,使用 goto 看起来很自然。

两个问题:

  1. 我应该替换这个 goto 吗?
  2. 有没有一种优雅的方法来替换这个 goto?

谢谢

Eri*_* J. 5

Goto,就像核能或培根一样,本质上并不邪恶。这是你用它做什么的问题。

当前的代码结构相当清晰。Goto 未用于创建意大利面条式代码

话虽如此,我仍然会用while循环替换它。 Goto可能是一个滑坡。

bool passwordIsOK = false;
while (!passwordIsOK && Retries < 3)
{
    // Existing code, without "goto start;".  Set passwordIsOK = true when appropriate.
    // See also @Sriram's comment about using "throw" rather than "throw ex".
}
Run Code Online (Sandbox Code Playgroud)