我用递归写了一段代码,需要在满足条件的时候中断这个递归,并返回当前值,如下:
function GetComponent(ComponentClassName:string;AOwner:TComponent):TComponent;
var
   i:integer;
begin
   Result:=nil;
   for i:=0 to AOwner.ComponentCount-1 do
   begin
      if(AOwner.Components[i].ClassName=ComponentClassName)then
      begin
        Result:=AOwner.Components[i];//满足条件的时候结束递归,返回此时的值
        exit;
      end
      else
         GetComponent(ComponentClassName,AOwner.Components[i]);//递归调用
   end;
end;这个函数在其它地方调用,递归查找某个Component到符合条件的时候就结束递归并返回当前值,如:Componetent:=GetCompontent('TEdit',Application);

解决方案 »

  1.   

    不好意思,刚才话还没说完,现在递归查找每个Component是没有问题,但是每次返回结果都是nil,我知道这是运行到Exit语句后返回了当前的这个函数的执行,而以前保留在堆栈中的循环并没有结束,所以Exit返回后又继续执行前面的循环了,要怎么才能避免这种情况,当运行到Exit的是否就结束递归呢?
      

  2.   

    就在那后面加个Break
    意思就是只要满足条件不管什么都结束循环