Rm5*_*558 4 c# readability goto try-catch
在这里使用 goto 似乎很自然。
一个项目需要读取pdf文件,pdf文件可以是以下之一。
只有使用正确的密码才能访问文件,无法预先知道文件需要哪个密码。我们必须尝试所有情况,(包括没有密码)。如果以上密码均无效,则抛出异常。
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 看起来很自然。
两个问题:
谢谢
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)