尝试将Delphi
代码的这一位转换为C#
,我对else
语句的后续if/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;
我知道您不必使用开头/结尾,但到目前为止我在此代码中看到的所有内容都使用了它。我还读到您在语句的;
部分中不需要if
,并且;
之后的第一个else
是{{1}的结尾}}
我的猜测是else
以及else
下的所有内容都是except
语句的一部分。
注意:如果我可以实际调试,这将很容易,但不幸的是,我只是被给予代码和函数的片段,无需真正的上下文进行转换。
答案 0 :(得分:10)
我建议您阅读文档If Statements。
在else
之后发表声明。每个语句(结构化或非结构化)都可以用分号分隔符;
结束。
声明可以是compound。在这种情况下,它被包含在begin/end
构造中。
在您的情况下,else
语句以Year := DefaultYear;
我建议始终使用'end / end'对,即使语句是单行。代码更具可读性,如果您稍后添加一行,则会出现更少的错误。
答案 1 :(得分:6)
else
分支包含
下一个语句(方法调用,赋值等)
if x=5 then
DoThis
else
DoThat; // <-- This is the complete else branch
或标有begin
和end
if x=5 then
DoThis
else
begin // <-- Here starts the else branch
DoThat;
DoSomethingElse;
end; // <-- Here ends the else branch
所以在你的情况下,这是整个else
分支。
Year:=Defaultyear;
旁注:
格式化在这里无关紧要。它仅用于可读性目的。只有begin
和end
会更改else
分支内的语句数量。
答案 2 :(得分:1)
除了上面提到的“阅读文档”,如果你需要一个可视化工具来帮助你跟踪Delphi 7中的if / else对和其他东西,我建议你安装Castalia工具。这对你有很大的帮助。
答案 3 :(得分:1)
我发现总是使用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;