0

I'm wondering how I can perform serialization of a generic TObjectList<T> container. Basically, I want to store different objects in that list, but all objects will descend from TSerializable, which is defined as follows:

  TSerializable = class abstract(TObject)
  public
    { Public declarations }
    procedure LoadFromStream(const S: TStream); virtual; abstract;
    procedure SaveToStream(const S: TStream); virtual; abstract;
  end;

Now, let's say I have these classes defined somewhere in my app:

type
    TExampleClass = class(TSerializable)
    private
        { Private declarations }
        FIntProp: Integer;
    public
        { Public declarations }
        constructor Create();

        procedure LoadFromStream(const S: TStream); override;
        procedure SaveToStream(const S: TStream); override;

        property IntProp: Integer read FIntProp write FIntProp;
    end;

    TAnotherExample = class(TSerializable)
    private
        { Private declarations }
        FStringProp: String;
    public
        { Public declarations }
        constructor Create();

        procedure LoadFromStream(const S: TStream); override;
        procedure SaveToStream(const S: TStream); override;

        procedure ReverseStringProp();

        property StringProp: String read FStringProp write FStringProp;
    end;

I'm planning to store such objects in a list:

var
    MS: TMemoryStream;
    SomeList: TObjectList<TSerializable>;
begin
    MS := TMemoryStream.Create();
    SomeList := TObjectList<TSerializable>.Create(True);
    try
        SomeList.Add(TExampleClass.Create());
        SomeList.Add(TAnotherClass.Create());

        TExampleClass(SomeList[0]).IntProp := 1992;
        TAnotherClass(SomeList[1]).StringProp := 'Some value';

        //  Here, a method to serialize the list...
        SerializeList(SomeList, MS);

        //  Clear the list and reset position in the stream.
        SomeList.Clear();
        MS.Seek(0, soFromBeginning);

        //  Unserialize the list.
        UnserializeList(SomeList, MS);

        //  Should display "Some value".
        Writeln(TAnotherClass(SomeList[1]).StringProp);
    finally
        SomeList.Free();
        MS.Free();
    end;
end;

Now, how could I possibly serialize the whole list to stream and then re-create the list from that stream?

What I was thinking about was:

  1. Iterate through the list.
  2. Write each object's class name to the stream first.
  3. Call SaveToStream() on that object.

But for that approach to work, I would need to create some kind of a class register, which would be some kind of a dictionary to store known classes. It sounds like a good idea, but then I would need to call some RegisterClass() method to add every new class to the dictionary, and I don't like that way too much.

Is there any other way, or should I just do it the way I proposed?

Thanks a bunch.

4

1 回答 1

1

谢谢你们的提示。我决定使用我自己的方法,这可能不是最好的方法,但适合我的小项目的需要。

我想有人可能会对这种方法感兴趣,所以我把它贴在这里。

基本上,我决定建立一个基类TSerializable

type
  TSerializable = class abstract(TObject)
  public
    { Public declarations }
    procedure LoadFromStream(const S: TStream); virtual; abstract;
    procedure SaveToStream(const S: TStream); virtual; abstract;
  end;

每个后代类都需要分别实现LoadFromStream()SaveToStream()处理保存到流。编写一些通用方法可能会很好,它们会自动加载/保存所有类属性。

然后,我有这个小班:

type
  TSerializableList = class(TObjectList<TSerializable>)
  public
    procedure Serialize(const S: TStream);
    procedure UnSerialize(const S: TStream);
  end;

代码是:

{ TSerializableList }

procedure TSerializableList.Serialize(const S: TStream);
var
  CurrentObj: TSerializable;
  StrLen, StrSize: Integer;
  ClsName: String;
begin
  S.Write(Self.Count, SizeOf(Integer));
  for CurrentObj in Self do
  begin
    ClsName := CurrentObj.QualifiedClassName();
    StrLen := Length(ClsName);
    StrSize := SizeOf(Char) * StrLen;

    S.Write(StrLen, SizeOf(Integer));
    S.Write(StrSize, SizeOf(Integer));
    S.Write(ClsName[1], StrSize);

    CurrentObj.SaveToStream(S);
  end;
end;

procedure TSerializableList.UnSerialize(const S: TStream);
var
  I, NewIdx, TotalCount, Tmp, Tmp2: Integer;
  ClsName: String;
  Context: TRttiContext;
  RttiType: TRttiInstanceType;
begin
  Context := TRttiContext.Create();
  try
    S.Read(TotalCount, SizeOf(Integer));
    for I := 0 to TotalCount -1 do
    begin
      S.Read(Tmp, SizeOf(Integer));
      S.Read(Tmp2, SizeOf(Integer));

      SetLength(ClsName, Tmp);
      S.Read(ClsName[1], Tmp2);

      RttiType := (Context.FindType(ClsName) as TRttiInstanceType);
      if (RttiType <> nil) then
      begin
        NewIdx := Self.Add(TSerializable(RttiType.MetaclassType.Create()));
        Self[NewIdx].LoadFromStream(S);
      end;
    end;
  finally
    Context.Free();
  end;
end;

又快又脏,但可以满足我的需要。

注意 由于代码使用扩展的 RTTI,它不会在旧的 Delphi 版本中编译。此外,您可能需要添加{$STRONGLINKTYPES ON}您的 DPR 文件或发明一些其他机制,以便链接器不会跳过您的课程(David Heffernan在此处提出一种方法)

于 2012-12-19T20:35:49.650 回答