语句

(1)while语句和repeat语句

含义:while-do 循环语句和 repeat-until 语句的不同点在于repeat 循环语句的代码至少要执行一次。从下面的简例很容易理解这一点:

while (I <= 100) and (J <= 100) do begin
  // use I and J to compute something...
  I := I + 1;
  J := J + 1;
end;

repeat
  // use I and J to compute something...
  I := I + 1;
  J := J + 1;
until (I > 100) or (J > 100);

​ 从上可见即使 I 或 J 的初始值大于100,repeat-until循环中的代码也仍会执行一次。

(2)with语句

含义:with语句是一种用于简化代码的语句。 如你要访问一个记录类型变量(或一个对象),用with语句就不必每次重复变量的名字。例如:

type
  Date = record
    Year: Integer;
    Month: Byte;
    Day: Byte;
  end;

var
  BirthDay: Date;

begin
  BirthDay.Year := 1997;
  BirthDay.Month := 2;
  BirthDay.Day := 14;
end;

​ 可以用with语句改进后半部分代码,如下:

begin
  with BirthDay do begin
    Year := 1995;
    Month := 2;
    Day := 14;
  end;
end;

​ 在Delphi程序中,这种方法能用于访问控件和类变量。现在通过with语句访问列表框的条目,我们重写上面循环例子的最后部分:

procedure TForm1.WhileButtonClick(Sender: TObject);
var
  I: Integer;
begin
  with ListBox1.Items do begin
    Clear; // shortcut
    Randomize;
    I := 0;
    while I < 1000 do begin
      I := I + Random (100);
      // shortcut:
      Add ('Random Number: ' + IntToStr (I));
    end;
  end;
end;

(3)break语句

含义:强制退出最近的一层循环

(注意:只能放在循环里;而且是只能跳出最近的一层循环),用于从for、while、repeat语句中强制退出类似于C/C++等语言中的break的功能

应用举例-例:循环提取一个字符串,直到接收到想要的字符串结束循环

var s:string;
begin
  while True do begin
    ReadLn(s);
    try
      if s:='' then break;
        WriteLn(s);
  end;
end;

​ break的英文字面意思就是打断,在循环中,用它表示停止本循环。注意,它是停止本循环,比如以下多层循环,如果要打断每一层,在每一层的循环中都要用一个break语句。

while 条件关系 do begin
	while 条件关系 do begin
		while 条件关系 do begin
			ShowMessage('Loop3');
			break;
		end;
		ShowMessage('Loop2');
		break;
	end;
	ShowMessage( 'Loop1');
	break;
end;

​ 所以在应用程序设计中,死机是最大的BUG,要坚决杜绝死机的可多写退出,不要客惜你的代码,多用break,多写退出条件

(4)continue语句

含义:用于从for、while、repeat语句中结束循环内的本次处理,继续从循环体的开始位置继续执行,类似于C/C++等语言中的continue的功能,即该过程使控制流从当前位置跳过后面的语句继续循环。

应用举例-例:i的循环

procedure test();
var
	i,j:Integer;
begin
	i:=0;
	j:=0;
	repeat
		if i>100 then break
		else begin
			inc(i);
			continue;
		end
		inc(j);
	until j>1;
end;

(5)exit语句

含义:用于从当前代码块中退出。若该代码是主程序,则终止该程序。如果是函数或过程,则立即终止该函数或过程

应用举例-例:对数据集进行复制,如果数据集没有打开则退出当前过程或函数。

begin
  if Query1.Active = False then
    Exit;
  if SaveDialog1.Execute then begin
    Table1.TableName:= SaveDialog1.FileName;
    with BatchMovel do begin
      Source:= Query1;
      Destination:= Tablel;
      Mode:= batCopy;
      Execute;
      ShowMessage(IntToStr(MovedCount)+'records copied');
    end;
  end;
end;
posted @ 2023-02-15 15:39  德琪  阅读(27)  评论(0编辑  收藏  举报