Delphi: Store data in somekind of structure

前端 未结 2 1958
礼貌的吻别
礼貌的吻别 2020-12-28 11:40

For a simulation program I\'m working in Delphi 2010. The simulation isn\'t a problem but I need to use large collection of data which gives a problem. The data is available

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-28 11:42

    Add SaveToStream() and LoadFromStream() methods to your data object which, well, save the data to a stream and load data from a stream.

    type
      TMyData = class(TObject)
      private
        FChildProducts: TList;
        FProductnumber : integer;
        FClean: boolean;
      public
        procedure LoadFromStream(const aStream: TStream);
        procedure SaveToStream(const aStream: TStream);
      published
        property Productnumber: Integer read FProductnumber write FProductnumber;
        property Clean: Boolean reas FClean write FClean;
      end;
    
    procedure TMyData.LoadFromStream(const aStream: TStream);
    var x, cnt: Integer;
        cD: TMyData;
    begin
      aStream.Read(FProductnumber, SizeOf(FProductnumber));
      aStream.Read(FClean, SizeOf(FClean));
      // read number of child products
      aStream.Read(cnt, SizeOf(cnt));
      // load child objects
      for x := 1 to cnt do begin
         cD := TMyData.create;
         cD.LoadFromStream(aStream);
         FChildProducts.Add(cD);
      end; 
    end;
    
    procedure TMyData.SaveToStream(const aStream: TStream);
    var x: Integer;
    begin
      aStream.Write(FProductnumber, SizeOf(FProductnumber));
      aStream.Write(FClean, SizeOf(FClean));
      // save number of child products
      x := FChildProducts.Count;
      aStream.Write(x, SizeOf(x));
      // save child objects
      for x := 0 to FChildProducts.Count - 1 do
         (FChildProducts[x] as TMyData).SaveToStream(aStream);
    end;
    

    I assume you have some list of "root objects" so you can make an function or method which saves/loads them to/from stream ie

    function SaveDataList(const List: TList;const aFileName: string);
    var x: Integer;
        FS: TFileStream;
    begin
      FS := TFileStream.Create(aFileName, ...);
      try
         // save file version
         x := 1;
         FS.Write(x, SizeOf(x));
         // save number of products
         x := List.Count;
         FS.Write(x, SizeOf(x));
         // save objects
         for x := 0 to List.Count - 1 do
           (List[x] as TMyData).SaveToStream(FS);
      finally
         FS.Free;
      end;
    end;
    

    This is the general idea... how to load data back should be clear too. The file version thing is there so that when the data object changes (ie you add some property) you can increment the version number so that in the loading code you can load data into right version of the data object.

提交回复
热议问题