您可以通过定义如下的另一个 TComponent 后代序列化未封装在 TComponent 中的 TCollection :
type
TCollectionSerializer = class(TComponent)
protected
FCollectionData: string;
procedure DefineProperties(Filer: TFiler); override;
public
procedure WriteData(Stream: TStream);
procedure ReadData(Stream: TStream);
//
procedure LoadFromCollection(ACollection: TCollection);
procedure SaveToCollection(ACollection: TCollection);
end;
DefineProperties、WriteData和ReadData实现细节:
procedure TCollectionSerializer.WriteData(Stream: TStream);
var
StrStream: TStringStream;
begin
StrStream:=TStringStream.Create;
try
StrStream.WriteString(FCollectionData);
Stream.CopyFrom(StrStream,0);
finally
StrStream.Free;
end;
end;
procedure TCollectionSerializer.ReadData(Stream: TStream);
var
StrStream: TStringStream;
begin
StrStream:=TStringStream.Create;
try
StrStream.CopyFrom(Stream,0);
FCollectionData:=StrStream.DataString;
finally
StrStream.Free;
end;
end;
procedure TCollectionSerializer.DefineProperties(Filer: TFiler);
begin
inherited;
//
Filer.DefineBinaryProperty('CollectionData', ReadData, WriteData,True);
end;
LoadFromCollection和SaveToCollection的模板:
procedure TCollectionSerializer.LoadFromCollection(ACollection: TCollection);
var
CollectionStream: TStream;
begin
CollectionStream:= TCollectionStream.Create(ACollection);
try
ReadData(CollectionStream)
finally
CollectionStream.Free;
end;
end;
procedure TCollectionSerializer.SaveToCollection(ACollection: TCollection);
var
CollectionStream: TStream;
begin
CollectionStream:= TCollectionStream.Create(ACollection);
try
WriteData(CollectionStream);
finally
CollectionStream.Free;
end;
end;
关于TCollectionStream:
它应该是一个 TStream 后代,具有一个以TCollection作为参数并设计为像 TFileStream 一样的丰富创建者。你必须实施它。免责声明:我从未测试过,但我可以说 TFileStream 工作(用于流式传输外部文件)。
结论:
这个组件的灵感来自于在 DFM 中序列化 Delphi XE (RCData) 下的外部文件的 VCL 方式。它必须与在设计时进行序列化的组件编辑器(您还必须基于 TComponentEditor 实现)一起注册。