代码为:
Type
  TmyRec = Record
    Name : String;
    Caption : String;
    Parent : String;
  End;
  TForm1 = TForm1(TForm) 
    private
       ....
    public
       RecComp : Array of TmyRec;procedure TForm1.Button1OnClick(Sender : TObject);
var i : Integer;
begin
  For i := 0 to CompontCount - 1 do
    begin
      If (Components[i] is TMenuItem) then
      begin
        RecComp[i].Name := Components[i].name;  //运行时报错
        RecComp[i].Caption := Components[i].Caption;
        RecComp[i].Parent := '';   
      end;
    end;
end;
上面是我的代码,因为是第一次用记录类型的可变数组,所以出了问题,但是找不到解决办法,请高手指点。问题:当程序一执行到RecComp[i].Name := Components[i].name时就出错。什么原因呢?
是否是声明可变记录类型数组时必先初始化?

解决方案 »

  1.   

    动态数组使用前需要指定大小,加上SetLength(recComp,ComponentCount)
      

  2.   

    万分感谢,不过,SetLength的第二个参数比Component小,具体数字也不知道是多少?
    这种情况下该怎么处理?如使用SetLength(recComp,ComponentCount),
    那么我遍力数组时有没有影响?
      

  3.   

    你就在循环里第一句写
    setlength(recomp,length(recomp)+1);
    然后再赋值
      

  4.   

    Type
      TmyRec = Record
        Name : String;
        Caption : String;
        Parent : String;
      End;
      TForm1 = TForm1(TForm) 
        private
           ....
        public
           RecComp : TStrings;//这里改了。procedure TForm1.Button1OnClick(Sender : TObject);
    var i : Integer;
    vRec:TMyRec;
    begin
      For i := 0 to CompontCount - 1 do
        begin
          If (Components[i] is TMenuItem) then
          begin
            vRec.Name:=Components[i].name;
            vRec.Caption:=Components[i].Caption;
            vRec.Parent:='';
            RecComp.AddObject(IntToStr(i),vRec);
          end;
        end;
    end;