序列化与反序列化

昨天,听大佬们在聊序列化,有提到xml,json,dfm

xml,json适合 公用接口,对于对象序列化,delphi的dfm 至少领先30年

所以,delphier 要明白,真正好的东西 就在身边  

delphi 的很多东西的思想都是非常先进的

delphi 只是用的人少了,但这工具,这语言并不比其他的差

群里崇拜的大佬,汇编,c++,delphi 都会,但还是在用delphi

这也给了我不丢下她的理由

delphi 序列化的 两种方式

一,资源序列化的简单方法:用途,比如  我们想实现界面数据暂存,每 5秒 暂存一次,可用下列方法

//写入

procedure TFrmMain.btn_writeClick(Sender: TObject);
var
fs: TFileStream;
i: Integer;
lpath,lstr: string;
begin //序列化
lpath := ExtractFilePath(ParamStr(0));
fs := TFileStream.Create(lpath + 'serialization.txt', fmCreate);
for i := 0 to Self.ComponentCount - 1 do
begin
fs.WriteComponentRes(Self.Components[i].ClassName, Self.Components[i]);
end;

fs.free();

lstr := ComponentToStr(Memo1);


end;

//读取

procedure TFrmMain.btn_readClick(Sender: TObject);

var
ts: TStream;
i: integer;
lpath: string;
begin //反序列化

lpath := ExtractFilePath(ParamStr(0));


ts := TFileStream.Create(lpath + 'serialization.txt',fmOpenRead);
for i := 0 to Self.ComponentCount - 1 do
ts.ReadComponentRes(Self.Components[i]);
ts.Free();

end;

二,dfm方式序列化,此方法 和dfm文件的方式一样,可很好的阅读,同样可用于数据暂存,但没上面的方便,上面可存在一个文件,而此方法适合每个组件一个文件,可能我来没找到合适的方法

function ComponentToStr(AComponent: TComponent): string;
var
BinStream: TMemoryStream;
StrStream: TStringStream;
s: string;
begin
BinStream := TMemoryStream.Create;
try
StrStream := TStringStream.Create(s);
try
BinStream.WriteComponent(AComponent);
BinStream.Seek(0, soFromBeginning);
ObjectBinaryToText(BinStream, StrStream);
StrStream.Seek(0, soFromBeginning);
Result := StrStream.DataString;
finally
StrStream.Free;
end;
finally
BinStream.Free
end;
end;

function StrToComponent(const Value: string;
Instance: TComponent): TComponent;
var
StrStream: TStringStream;
BinStream: TMemoryStream;
begin
StrStream := TStringStream.Create(Value);
try
BinStream := TMemoryStream.Create;
try
ObjectTextToBinary(StrStream, BinStream);
BinStream.Seek(0, soFromBeginning);
Result := BinStream.ReadComponent(Instance);
finally
BinStream.Free;
end;
finally
StrStream.Free;
end;
end;

原文地址:https://www.cnblogs.com/iwana/p/13813954.html