这个 else 语句在哪里结束?

Where does this `else` statement end?

试图将这段 Delphi 代码转换为 C#,我对 if/else 语句的以下 else 部分实际上在哪里结束感到困惑。以下是代码的确切格式:

 try
   Root:=ExtractFileRoot(FileName);
   ErrorStr:=ExtractFileRoot(FileName)+' invalid name';
   if not GetNextNumericSegment(Root,Segment) then exit;  
   if length(Segment) = 4 then
   begin
      Year:=StrToInt(Segment);
      GetnextNumericSegment(Root,Segment)
   end
   else // Where does this else statement end?
       Year:=Defaultyear;
    ErrorStr:=ExtractFileRoot(FileName)+' invalid';
   if Length(Segment) <> 3 then exit;
   Jday:=StrToInt(Segment);
    ErrorStr:=ExtractFileRoot(FileName)+' Bad File';
   if not GetNextNumericSegment(Root,Segment) then exit;  // bad Time of day
   GetTimeFromFileName:=EncodeDate(Year,1,1)+Jday-1+
                        EncodeTime(StrToInt(Copy(Segment,1,2)),StrToInt(Copy(Segment,3,2)),StrToInt(Copy(Segment,5,2)),0);
 except
       GetTimeFromFileName:=0;
 end;

我知道您不必使用 begin/end,但到目前为止我在这段代码中看到的所有内容都使用了它。我还读到在语句的 if 部分不需要 ; 并且 else 之后的第一个 ;else.

我的猜测是 else 下到 except 的所有内容都是 else 语句的一部分。

注意:如果我可以实际调试,这将很容易,但不幸的是,我只是在没有实际上下文的情况下获得代码和函数片段以进行转换。

一个 else 分支包含

  • 下一条语句(方法调用、赋值等)

    if x=5 then
      DoThis
    else
      DoThat; // <-- This is the complete else branch
    
  • 或标有beginend

    的区块
    if x=5 then
      DoThis
    else
    begin // <-- Here starts the else branch
      DoThat; 
      DoSomethingElse; 
    end; // <-- Here ends the else branch
    

因此在您的情况下,这是整个 else 分支。

Year:=Defaultyear;

旁注: 格式化在这里无关紧要。它仅用于可读性目的。只有 beginend 会更改 else 分支内的语句数量。

我建议阅读文档,If Statements

else 后跟一个语句。每个语句(结构化或非结构化)都可以用分号分隔符结束 ;.

语句可以是compound。在那种情况下,它包含在 begin/end 构造中。

在您的情况下,else 语句以 Year := DefaultYear;

结尾

我建议始终使用“begin/end”对,即使语句是一行。代码更具可读性,如果您稍后添加一行,则错误会更少。

除了上面提到的“阅读文档”之外,如果您需要一个可视化工具来帮助您跟踪 if/else 对和其他 Delphi 7,我建议您安装 Castalia 工具.对你会有很大的帮助。

我发现无论有多少语句,始终使用 Begin/End 很有用。例如;

If A = 1 then
    Begin
      // Every line here executes if A = 1
      ShowMessage('A does in fact equal 1');
      ShowMessage('These messages can be annoying')
    end 
      else
    Being
      // Everything here executes if A doesn't equal 1
      ShowMessage('A was not equal to 1');
      ShowMessage('This is still an annoying message') 
    End;