这是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;
我不知道为什么。我在这个程序的其他部分有非常相似的代码,它们按预期工作。
我做错了什么?
答案 0 :(得分:1)
当返回的对象为nil
时,您确认SelectedIndex
值实际上是否有效?您的代码中存在逻辑错误,当ListBox不为空时,{J}允许SelectedIndex
为-1
。您的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;