gpt4 book ai didi

delphi - Delphi/Pascal 的正确结构语法 if then begin end and ;

转载 作者:行者123 更新时间:2023-12-03 14:37:21 24 4
gpt4 key购买 nike

距离我上次用 Pascal 写作已经过去了大约 20 年。我似乎无法正确使用语言的结构元素,因为我使用 beginend 嵌套 if then block 。例如,这会导致编译器错误“需要标识符”

procedure InitializeWizard;
begin
Log('Initialize Wizard');
if IsAdminLoggedOn then begin
SetupUserGroup();
SomeOtherProcedure();
else begin (*Identifier Expected*)
Log('User is not an administrator.');
msgbox('The current user is not administrator.', mbInformation, MB_OK);
end
end;
end;

当然,如果我删除与它们关联的 if then block 和 begin end block ,那么一切都会正常。

有时我正确地理解了这种语法,并且效果很好,但是当嵌套 if then else block 时,问题会变得更加严重。

仅仅解决问题还不够。我想更好地了解如何使用这些 block 。我显然缺少一个概念。来自 C++ 或 C# 的某些东西可能会从我大脑的另一部分潜入并扰乱我的理解。我读过一些关于它的文章,我想我理解它,但后来又不明白。

最佳答案

您必须将每个 begin 与同一级别的 end 相匹配,例如

if Condition then
begin
DoSomething;
end
else
begin
DoADifferentThing;
end;

如果您愿意,可以在不影响布局的情况下缩短所使用的行数。 (不过,当您第一次习惯语法时,上面的内容可能会更容易。)

if Condition then begin
DoSomething
end else begin
DoADifferentThing;
end;

如果您正在执行单个语句,则 begin..end 是可选的。请注意,第一个条件不包含终止 ;,因为您尚未结束该语句:

if Condition then
DoSomething
else
DoADifferentThing;

分号在 block 中的最后一个语句中是可选的(尽管即使它是可选的,我通常也会包含它,以避免将来在添加行并忘记同时更新前一行时出现问题)。

if Condition then
begin
DoSomething; // Semicolon required here
DoSomethingElse; // Semicolon optional here
end; // Semicolon required here unless the
// next line is another 'end'.

您也可以组合单个和多个语句 block :

if Condition then
begin
DoSomething;
DoSomethingElse;
end
else
DoADifferentThing;

if Condition then
DoSomething
else
begin
DoADifferentThing;
DoAnotherDifferentThing;
end;

代码的正确用法是:

procedure InitializeWizard;
begin
Log('Initialize Wizard');
if IsAdminLoggedOn then
begin
SetupUserGroup();
SomeOtherProcedure();
end
else
begin
Log('User is not an administrator.');
msgbox('The current user is not administrator.', mbInformation, MB_OK);
end;
end;

关于delphi - Delphi/Pascal 的正确结构语法 if then begin end and ;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28221394/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com