2

我有一个同步滚动框的简单示例,在其中我通过单选按钮控制哪一侧同步 - 同步左侧或右侧。当我编译时,我得到编译器消息:

[dcc32 警告] Unit1.pas(51): W1036 变量“ScrlBox1”可能尚未初始化

[dcc32 警告] Unit1.pas(51): W1036 变量“ScrlBox2”可能尚未初始化

这是一个简单的例子:

procedure TForm1.Button1Click(Sender: TObject);
var
  ScrlBox1, ScrlBox2: TScrollBox;
begin

    if radiobtn_SyncLeftSides.Checked then // Snyc Left side
    begin
      ScrlBox1 := ScrollBoxLeft1;
      ScrlBox2 := ScrollBoxLeft2;
    end
    else if radiobtn_SyncrightSides.Checked then  // Snyc Right side
    begin
      ScrlBox2 := ScrollBoxRight1;
      ScrlBox1 := ScrollBoxRight2;
    end;

    // Sync scroll boxes
    ScrlBox2.VertScrollBar.Position := ScrlBox1.VertScrollBar.Position;
    ScrlBox2.HorzScrollBar.Position := ScrlBox1.HorzScrollBar.Position;

end;

这里有什么问题?

如果我在开头添加此消息,则消息消失:

ScrlBox1:= TScrollBox.Create(nil);
ScrlBox2:= TScrollBox.Create(nil);

但我不认为创建滚动框变量是必要的,对吧?这些只是表单控件的变量指针。

4

1 回答 1

6

如果and都未选中,则在使用 and 变量之前不会对其进行 初始化。这就是编译器所抱怨的。radiobtn_SyncLeftSidesradiobtn_SyncrightSidesScrlBox1ScrlBox2

procedure TForm1.Button1Click(Sender: TObject);
var
  ScrlBox1, ScrlBox2: TScrollBox;
begin
  if radiobtn_SyncLeftSides.Checked then // Snyc Left side
  begin
    ScrlBox1 := ScrollBoxLeft1;
    ScrlBox2 := ScrollBoxLeft2;
  end
  else if radiobtn_SyncrightSides.Checked then  // Snyc Right side
  begin
    ScrlBox2 := ScrollBoxRight1;
    ScrlBox1 := ScrollBoxRight2;
  end else
  begin
    // NOT INITIALIZED HERE!!!!!
  end;

  // Sync scroll boxes
  ScrlBox2.VertScrollBar.Position := ScrlBox1.VertScrollBar.Position;
  ScrlBox2.HorzScrollBar.Position := ScrlBox1.HorzScrollBar.Position;
end;

如果您不想同步滚动,您应该只Exit执行以下过程:

procedure TForm1.Button1Click(Sender: TObject);
var
  ScrlBox1, ScrlBox2: TScrollBox;
begin
  if radiobtn_SyncLeftSides.Checked then // Snyc Left side
  begin
    ScrlBox1 := ScrollBoxLeft1;
    ScrlBox2 := ScrollBoxLeft2;
  end
  else if radiobtn_SyncrightSides.Checked then  // Snyc Right side
  begin
    ScrlBox2 := ScrollBoxRight1;
    ScrlBox1 := ScrollBoxRight2;
  end else
  begin
    Exit; // <-- HERE
  end;

  // Sync scroll boxes
  ScrlBox2.VertScrollBar.Position := ScrlBox1.VertScrollBar.Position;
  ScrlBox2.HorzScrollBar.Position := ScrlBox1.HorzScrollBar.Position;
end;
于 2016-02-25T22:09:17.913 回答