delphi持久类TPersistent派生的组件TComponent的序列化和反序列化

delphi持久类TPersistent派生的组件TComponent的序列化和反序列化

一、概念:组件的序列化和反序列化

组件的序列化 (serialization):将组件对象的状态信息转换为可以存储或传输的形式的过程。 
与组件序列化相对的是组件反序列化:它将流转换为对象。这两个过程结合起来,可以轻松地存储和传输数据。 
序列化的目的 :
  1、以某种存储形式使自定义对象持久化; 
  2、将对象从一个地方传递到另一个地方。 
  3、使程序更具维护性 
在Delphi中 只要从 TPersistent继承后就会有序列化的功能。 
在TPersistent中的定义 
procedure DefineProperties(Filer: TFiler); virtual; 

二、用途

可以将组件状态到资源文件,在需要调用时将其还原。比如:关闭App后再次打开。显示某个窗体(但不能是主窗体)或组件前,将之间保存的状态进行还原,感觉就是上次关闭它之间的样子。

三、实现

const FTPersistentFile ='FTPersistentFile.res';

var  FTPersistentFilePath:string;

1、保存某个组件状态到外部资源文件:

var
  LFileStream:TFileStream;
  LComponentCount:Integer;
begin
  try
    AndoidRequestPermissions(['管理文档','读取文件','写入文件']);//:合称"存储权限"
    //:你需要实现Android运行时的动态权限申请和用户确认
  finally
    try
      SubPathOfAppPublished; //:你写的通用平台的设置路径的方法
    finally
      FTPersistentFilePath:=GetSubPathOfAppPublished('Download','files');   //:你写的通用平台的获取路径的方法
    end;
  end;
  //反序列化:
  //组件状态持久序列化读文件:FTPersistentFilePath FTPersistentFile
  if FileExists(FTPersistentFilePath + FTPersistentFile)=false then exit;

  LFileStream := TFileStream.Create(
    FTPersistentFilePath + FTPersistentFile,fmOpenRead);
  try
    for LComponentCount := 0 to Self.ComponentCount - 1 do
    begin
      if (Self.Components[LComponentCount].ClassType = TMemo)
        and not (csDesigning in Self.Components[LComponentCount].ComponentState)
        then
      LFileStream.ReadComponentRes(Self.Components[LComponentCount]);
    end; //}
  finally
    LFileStream.Free;
  end;
end;

2、在需要的时候从资源文件中将组件的状态读入

扫描二维码关注公众号,回复: 11329010 查看本文章

var
  LFileStream:TFileStream;
  LComponentCount:Integer;  

  //反序列化:
  //组件状态持久序列化读文件:FTPersistentFilePath FTPersistentFile :

begin  

  try
    AndoidRequestPermissions(['管理文档','读取文件','写入文件']);//:合称"存储权限"
    //:你需要实现Android运行时的动态权限申请和用户确认
  finally
    try
      SubPathOfAppPublished;  //:你写的通用平台的设置路径的方法
    finally
      FTPersistentFilePath:=GetSubPathOfAppPublished('Download','files');   //:你写的通用平台的获取路径的方法
    end;
  end;

  LFileStream := TFileStream.Create(
    FTPersistentFilePath + FTPersistentFile,fmOpenRead);
  try
    for LComponentCount := 0 to Self.ComponentCount - 1 do
    begin
      if (Self.Components[LComponentCount].ClassType = TMemo)
        and not (csDesigning in Self.Components[LComponentCount].ComponentState)
        then
      LFileStream.ReadComponentRes(Self.Components[LComponentCount]);
    end; 
  finally
    LFileStream.Free;
  end;

end;

上文方法引自:https://blog.csdn.net/lailai186/article/details/8077161

附相关文章:

delphi XE用TPath类获取路径IDE解析不了类方法编译也要报错:

https://blog.csdn.net/pulledup/article/details/105767353 

喜欢的话,就在下面点个赞、收藏就好了,方便看下次的分享:

猜你喜欢

转载自blog.csdn.net/pulledup/article/details/105768280
今日推荐