如果是从TComponent继承下来的东西,可以直接用TStream的方法
function ReadComponent(Instance: TComponent): TComponent;
function ReadComponentRes(Instance: TComponent): TComponent;
procedure WriteComponent(Instance: TComponent);
procedure WriteComponentRes(const ResName: string
Instance: TComponent);
具体可以查看
http://www.delphibbs.com/delphibbs/dispq.asp?LID=2421751
这个帖子非常好
如果是自己写的一个普通的类,可以考虑用我的方法
比如说有个类
TTest = class
private
nCount: Integer;
sName: string;
nWeight: double;
L: TList;
L1: TList;
public
constructor Create;
destructor Destroy
override;
procedure SaveToStream(var AStream: TMemoryStream);
procedure LaodFormStream(const AStream: TMemoryStream);
end;
procedure TTest.LaodFormStream(const AStream: TMemoryStream);
var
LCount: Integer;
I: Integer;
pt: TPt;
begin
if not Assigned(AStream) then Exit;
AStream.Position := 0;
AStream.ReadBuffer(nCount, sizeof(Integer));
AStream.ReadBuffer(Pointer(sName)^, sizeof(string));
AStream.ReadBuffer(nWeight, sizeof(double));
// 取链表
AStream.ReadBuffer(LCount, sizeof(LCount));
for I := L.Count - 1 downto 0 do TPt(L.Items).Free;
L.Clear;
for I := 0 to LCount - 1 do begin
pt := TPt.Create;
AStream.Read(pt.X, sizeof(double));
AStream.Read(pt.Y, sizeof(double));
AStream.Read(pt.Z, sizeof(double));
L.Add(pt);
end;
end;
procedure TTest.SaveToStream(var AStream: TMemoryStream);
var
I: Integer;
LCount: Integer;
pt: TPt;
begin
if not Assigned(AStream) then Exit;
AStream.Position := 0;
AStream.Write(nCount, sizeof(nCount));
AStream.Write(Pointer(sName)^, sizeof(sName));
AStream.Write(nWeight, sizeof(nWeight));
// 存链表
LCount := L.Count;
AStream.Write(LCount, sizeof(LCount));
for I := 0 to LCount - 1 do begin
pt := TPt(L.Items);
AStream.Write(pt.X, sizeof(double));
AStream.Write(pt.Y, sizeof(double));
AStream.Write(pt.Z, sizeof(double));
end;
AStream.SetSize(AStream.Position);
end;
然后通过这个Stream去LoadFromFile和SaveToFile,就可以把这个类的内容保存到文件里面去, http://delphibbs.com/delphibbs/dispq.asp?lid=3110533这个例子里面的东西是我存对象到数据库的例子,也是持久化对象了,几种数据类型基本上都考虑到了