这是我提出的解决方案。
我有一个基类
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;
负载的方法是这样的(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;
的基类可以提供加载和保存为德尔福默认类型的方法。然后我就可以创建一个配置我的应用程序是这样的:一个自定义的保存方法的
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;
这对我来说看起来相当不错。是什么让你觉得可能有更聪明的解决方案? – 2009-08-21 13:01:03
@Jeroen:在大多数情况下,当我在这里问我的经验,我得到了很多聪明的评论,改进和批评的建议:)除此之外,我想分享这段代码,以便其他人可以受益。 – jpfollenius 2009-08-24 06:25:40