-2

这是system.object:

  TTrendGroup = class(System.Object)
    SigList:ArrayList;
    Rate,Phase,Delay:SmallInt;
    RateIndex,PhaseIndex:SmallInt;
    firstTime:Boolean;
    base:integer;
    Enabled:Boolean;
    name:string;
    public
    constructor;
    method AddTGroup(signal:TTrendSignal);
    method Clear;
    method Poll(list:ArrayList);
    method ReadTGroup(bTGr:BinaryReader);
    method WriteTGroup(bTGw:BinaryWriter);
    method WriteSignals(bWSw:BinaryWriter);
    method ToString:String;override;
  end;

constructor TTrendGroup;
begin
  SigList := new ArrayList;
  Rate := 30;
  Phase := 0;
  Delay := Phase;
  RateIndex := 4;
  PhaseIndex := 0;
  firsttime := true;
  enabled := true;
  name := '';
end;

下面是我如何从上面的 system.object 创建一个对象并将其添加到我的 GroupList ListBox:

method HTrendFrm.AddGroup1_Click(sender: System.Object; e: System.EventArgs);
var
  i:integer;
  grp:TTrendGroup;
begin
  if ReadWrite then
  begin
    grp := new TTrendGroup;
    grp.name:='New Group';
    i := GroupList.Items.Add(grp);
    GroupList.SelectedIndex := i;
    grpName.Text := 'New Group';
    PollBtn.Checked := grp.Enabled;
    RateBox.SelectedIndex := grp.RateIndex;
    PhaseBox.SelectedIndex:= grp.PhaseIndex;
    SignalListBox.Items.Clear;
    UpdateButtons;
  end;
end;

这是我尝试检索刚刚添加回来的 system.object 的方法:

method HTrendFrm.GroupList_Click(sender: System.Object; e: System.EventArgs);
 var
  grp:TTrendGroup;
begin
  if (GroupList.SelectedIndex = -1) then exit;
  with GroupList do
  begin
    grp := TTrendGroup(items[SelectedIndex]); <<<<< HERE is WHERE THE PROBLEM IS. grp always returns NIL.
  end;
end;

我不知道为什么。我在这个程序的其他部分有非常相似的代码,它们按预期工作。

我究竟做错了什么?

4

1 回答 1

1

当返回的对象是nil时,您是否验证该SelectedIndex值实际上是有效的?您的代码中有一个逻辑错误,允许SelectedIndex-1ListBox 不为空时出现。您的if语句需要使用or运算符而不是and运算符:

// if (GroupList.Items.Count<=0) and (GroupList.SelectedIndex = -1) then exit;
if (GroupList.Items.Count<=0) or (GroupList.SelectedIndex = -1) then exit;
于 2012-04-06T21:04:24.150 回答