这是我提出的解决方案。
我有一个基类
TConfiguration = class
protected
type
TCustomSaveMethod = function (Self : TObject; P : Pointer) : String;
TCustomLoadMethod = procedure (Self : TObject; const Str : String);
public
procedure Save (const FileName : String);
procedure Load (const FileName : String);
end;
Load 方法如下所示(相应的 Save 方法):
procedure TConfiguration.Load (const FileName : String);
const
PropNotFound = '_PROP_NOT_FOUND_';
var
IniFile : TIniFile;
Count : Integer;
List : PPropList;
TypeName, PropName, InputString, MethodName : String;
LoadMethod : TCustomLoadMethod;
begin
IniFile := TIniFile.Create (FileName);
try
Count := GetPropList (Self.ClassInfo, tkProperties, nil) ;
GetMem (List, Count * SizeOf (PPropInfo)) ;
try
GetPropList (Self.ClassInfo, tkProperties, List);
for I := 0 to Count-1 do
begin
TypeName := String (List [I]^.PropType^.Name);
PropName := String (List [I]^.Name);
InputString := IniFile.ReadString ('Options', PropName, PropNotFound);
if (InputString = PropNotFound) then
Continue;
MethodName := 'Load' + TypeName;
LoadMethod := Self.MethodAddress (MethodName);
if not Assigned (LoadMethod) then
raise EConfigLoadError.Create ('No load method for custom type ' + TypeName);
LoadMethod (Self, InputString);
end;
finally
FreeMem (List, Count * SizeOf (PPropInfo));
end;
finally
FreeAndNil (IniFile);
end;
基类可以为 delphi 默认类型提供加载和保存方法。然后我可以为我的应用程序创建一个配置,如下所示:
TMyConfiguration = class (TConfiguration)
...
published
function SaveTObject (P : Pointer) : String;
procedure LoadTObject (const Str : String);
published
property BoolOption : Boolean read FBoolOption write FBoolOption;
property ObjOption : TObject read FObjOption write FObjOption;
end;
自定义保存方法的示例:
function TMyConfiguration.SaveTObject (P : Pointer) : String;
var
Obj : TObject;
begin
Obj := TObject (P);
Result := Obj.ClassName; // does not make sense; only example;
end;