退出Delphi中的"if"

use*_*591 6 delphi

你可以用break退出while循环.

如何退出if .

Delphi中有一种GOTO吗?

procedure ...
begin

  if .... then
    begin

      here the code to execute

      if (I want to exit = TRUE) then
        break or GOTO

      here the code not to execute if has exited

    end;

  here the code to execute

end;
Run Code Online (Sandbox Code Playgroud)

TLa*_*ama 11

比如Piskvor mentioned,使用嵌套的if语句:

procedure Something;
begin    
  if IWantToEnterHere then
  begin
    // here the code to execute    
    if not IWantToExit then
      // here the code not to execute if has exited
  end;    
  // here the code to execute
end;
Run Code Online (Sandbox Code Playgroud)

  • +1我同意这个.尽管Delphi支持goto和label,但这种用法会导致spagheti代码和维护噩梦.Gotos和标签让我想起了汇编等低级语言. (4认同)

Ari*_*The 2

您可以使用异常。

在内部 if 或循环中调用 Abort,并在您想要继续的地方捕获 EAbort 异常

procedure ...
begin

 try 
  if .... then
    begin

      (*      here the code to execute  *)

      if I_want-to-exit then Abort;

      (*      here the code not to execute if has exited *)

    end;
  
   except on E: EABORT do ;
   end;

   (*  here the code to execute *)
end;
Run Code Online (Sandbox Code Playgroud)

UPD。刚刚有人对此表示赞同。看来这个话题还没有被埋没很久。好的,然后快速总结一下评论中隐藏的内容。

这种方法可能不如 Marjan 的 try-exit-finally 方法,请参阅他的答案:https ://stackoverflow.com/a/11689392/976391

异常在 Delphi 中稍微便宜一些,Borland 在这方面拥有很少的专利,但仍然可能比+finally执行得更快。raiseexcept

OTOH,由于异常取消和可以使用不同的类别,这种方法可以概括为具有多个嵌套的可退出 if 块和不同的退出目标。我觉得代码更干净一点,更好地表达了开发人员(主题启动者)的思路,当 except-block 只是一个退出锚点时,真正的代码在它后面,而不是在它里面(就像finally-solution所需要的那样) )。

type EExitException1 = class(Exception) end;
type EExitException2 = class(Exception) end;
procedure ...
begin

 try 
  if .... then
    begin

      (*      here the code to execute  *)
       try
         if .... then
         begin

            (*      here the nested code to execute  *)


            if I_want-to-exit then raise EExitException1.Create();

            (** ...  **)
            if I_want-to-exit-far-away then raise EExitException2.Create();

            (*      here the code not to execute if if-block cancelled *)

         end; // if

       (*      here the code to execute  *)  

       if I_want-to-exit-outer-if-here then raise EExitException2.Create();

        (*      here the code not to execute  *)  

       except on E: EExitException1 do ; end; // killing the exception
           
       (*      here the code to execute after the outer if-block exit *)

    end;

   (* one more piece of skippable code *)
  
   except on E: EExitException2 do ; end;

   (*  here the code to execute yet again *)
end;
Run Code Online (Sandbox Code Playgroud)

然而,这种概括也往往很快就会变成意大利面条,只是另一种形式。

诚然,这个问题看起来很棘手,需要重构整个部分。如果不重构,所有解决方案都会以某种方式变得混乱。如果梯子,普通的旧的goto,旗帜变量 - 选择你的毒药。我们可以争论到底哪一个不那么丑,但它们都很丑。

  • @John 好吧,有 goto,肯定 goto 比例外更接近 goto (5认同)
  • 在我看来,使用异常的错误方式。更好的是使用 try if 123 then if 456 then exit;finally // 代码以任何方式执行,即使是退出端; (2认同)
  • 引发异常是“昂贵的”(当在循环中使用时,它会影响程序执行速度) (2认同)