请问如何将自定义的对象保存在流中,并恢复出来,救急!!(100分)

  • 主题发起人 netexplorer
  • 开始时间
N

netexplorer

Unregistered / Unconfirmed
GUEST, unregistred user!
自己创建了两个简单的类,其中tc2包含了列表,用于存放tc1的对象:
tc1=class(tcomponent)
public
i,j:integer;
str:string;
end;
tc2=class(tcomponent)
public
list:tlist;
test:string;
constructor create;
end;
然后创建一个tc2对象实例,并写入一个文件中。
var
stream:tmemorystream;
count1:integer;
c1:tc1;
c2:tc2;
begin
c2:=tc2.create;
for count1:=0 to 4 do
begin
c1:=tc1.Create(nil);
c1.i:=count1;
c1.j:=count1+2;
c1.str:=inttostr(count1);
c2.list.add(c1);
end;
showmessage(tc1(c2.list[3]).str);
c2.test:='leowangyu';
stream:=tmemorystream.Create;
stream.Writecomponent(c2);
stream.SaveToFile('1.txt');
end

这时,该文件只有11字节。好像并没有将tc2的实例保存下来。
试着恢复一下这个对象。
var
c2:tc2;
stream:tmemorystream;
begin
stream:=tmemorystream.Create;
stream.LoadFromFile('1.txt');
stream.Position:=0;
end;
结果在stream.ReadComponent(c2);执行时报错。
本来我也有心理准备,可能tc2中无法恢复list的值,但是至少应该将对象创建出来吧。
很郁闷,
请高手指点!
多谢!!
 
因为你的类内部有变量而TWriter事不认识你的内部变量的。
你需要覆盖TComponent的WriteState和ReadState
编程把你的List的内容存起来
 
顶部