将对象的 TList 保存在文本文件中
我有以下类:
type
TSong = class(TObject)
private
FArtist: String;
FTitle: String;
procedure SetArtist(Artist: String);
procedure SetTitle(Title: String);
public
property Artist: String read FArtist Write SetArtist;
property Title: String read FTitle Write SetTitle;
constructor Create(Artist, Title: String);
end;
type
TPlaylist = class(TList)
private
procedure ShowInListBox(Box: Pointer);
public
{ Public-Deklarationen }
end;
在运行时,我创建这些类的实例:
Playlist := TPlaylist.Create;
Playlist.Add(TSong.Create('Artist 1', 'Title 1'));
Playlist.Add(TSong.Create('Artist 2', 'Title 2'));
Playlist.Add(TSong.Create('Artist 3', 'Title 3'));
Playlist.Add(TSong.Create('Artist 4', 'Title 4'));
当程序关闭时,我想将这些数据保存到文本文件中。我该怎么做?
最好的方法可能是创建一个属于 TPlaylist 类的过程,对吗?
procedure SaveToTxtFile(fName: String);
这样的函数到底应该做什么?当程序再次启动时,我希望能够再次构建播放列表。
如果数据能保存在像这样的文本文件中那就太好了:
Artist 1///Title 1
Artist 2///Title 2
I have the following classes:
type
TSong = class(TObject)
private
FArtist: String;
FTitle: String;
procedure SetArtist(Artist: String);
procedure SetTitle(Title: String);
public
property Artist: String read FArtist Write SetArtist;
property Title: String read FTitle Write SetTitle;
constructor Create(Artist, Title: String);
end;
type
TPlaylist = class(TList)
private
procedure ShowInListBox(Box: Pointer);
public
{ Public-Deklarationen }
end;
At runtime, I create instances of these classes:
Playlist := TPlaylist.Create;
Playlist.Add(TSong.Create('Artist 1', 'Title 1'));
Playlist.Add(TSong.Create('Artist 2', 'Title 2'));
Playlist.Add(TSong.Create('Artist 3', 'Title 3'));
Playlist.Add(TSong.Create('Artist 4', 'Title 4'));
When the program is closed, I would like to save these data into a text file. How can I do this?
The best way would probably be to create a procedure which belongs to the TPlaylist class, right?
procedure SaveToTxtFile(fName: String);
What should such a function exactly do? When the program is started again, I would like to be able to build the playlist again.
It would be nice if the data would be saved in a text file like this:
Artist 1///Title 1
Artist 2///Title 2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你走在正确的轨道上。您尝试做的事情称为序列化,将对象转换为可流式传输的形式,例如文件。
您需要开发一种格式。确切的格式是什么并不重要,只要它一致并保留重建对象所需的所有数据即可。你说你想要一个文本文件,所以在这种情况下你可以通过使用内置文件 IO 的 TStringList 采取一些捷径。
尝试这样的事情:
你还想实现相反的反序列化。应该不会太难。
You're on the right track. What you're trying to do is called serialization, turning an object into a streamable form like a file.
You need to develop a format. Exactly what the format is doesn't matter, as long as it's consistent and preserves all of the data that you require to reconstruct the object. You say you want a text file, so you can take a bit of a shortcut in this case by using a TStringList, which has file IO built in.
Try something like this:
You'll also want to implement the inverse, deserialization. It shouldn't be too difficult.