⑶ 部件的寫入
TWriter對象中與寫入部件有關的方法有WriteSignature、WritePrefix、WriteComponent、WriteDescendant和WriteRootComponent。
WriteSignature方法用於往流中寫入Filer對象標簽。
procedure TWriter.WriteSignature;
begin
Write(FilerSignature, SizeOf(FilerSignature));
end;
FilerStgnature是字符串常量,其值為“TPF0”,代表對象標簽。
WritePrefix方法用於在寫入部件前寫入ffInherited和ffChildPos標志,這些標志表示部件的繼承特征和創建序值特征。
procedure TWriter.WritePrefix(Flags: TFilerFlags; AChildPos: Integer);
var
Prefix: Byte;
begin
if Flags <> [] then
begin
Prefix := $F0 or Byte(Flags);
Write(Prefix, SizeOf(Prefix));
if ffChildPos in Flags then WriteInteger(AChildPos);
end;
end;
如果ffChildPos置位,則存入部件在Owner中的創建序值。更詳細的信息請參閱TReader的ReadPrefix方法。
WriteComponent方法往流中寫入部件。
procedure TWriter.WriteComponent(Component: TComponent);
function FindAncestor(const Name: string): TComponent;
begin
…
end;
begin
Include(Component.FComponentState, csWriting);
if Assigned(FAncestorList) then
Ancestor := FindAncestor(Component.Name);
Component.WriteState(Self);
Exclude(Component.FComponentState, csWriting);
end;
方法中用Component的WritState方法寫入部件的屬性。在寫入之前將Component.FComponentState置為csWriting寫入完後再將csWriting復位。
WriteDescendant是根據祖先AAncestor的情況寫入部件Root。
procedure TWriter.WriteDescendent(Root: TComponent; AAncestor: TComponent);
begin
FRootAncestor := AAncestor;
FAncestor := AAncestor;
FRoot := Root;
WriteSignature;
WriteComponent(Root);
end;
方法先調用WriteSignature方法寫入Filer對象標簽。然後調用WriteComponent將部件Root寫入流。
WriteRootComponent方法則是調用WriteDescendant方法寫入部件,只是將後者的Ancestor參數以nil值傳入。
procedure TWriter.WriteRootComponent(Root: TComponent);
begin
WriteDescendent(Root, nil);
end;