【发布时间】:2026-02-22 16:40:01
【问题描述】:
我正在尝试实现一个配置文件类包装器,使用单个函数获取和设置属性值会更容易。
下面的代码是我想要实现的最低版本。
欢迎任何帮助。
unit Config;
interface
uses Rtti;
type
Group = class(TCustomAttribute)
strict private
FName: string;
public
constructor Create(const Name: string);
property Name: string read FName;
end;
IConfig = class
protected
function GetString: string;
procedure SetString(const Value: string);
end;
TConfig = class(IConfig)
public
[Group('Person')]
property Name: string read GetString write SetString;
[Group('Person')]
property City: string read GetString write SetString;
end;
implementation
{ Group }
constructor Group.Create(const Name: string);
begin
FName := Name;
end;
{ IConfig }
function IConfig.GetString: string;
begin
// Here I would need the following from the property that call this function:
// * Property name
// * Property attribute name
// This kind of code will not work, because it loop through all available properties
(*
var
ctx: TRttiContext;
objType: TRttiType;
Prop: TRttiProperty;
begin
ctx := TRttiContext.Create;
objType := ctx.GetType(Obj.ClassInfo);
for Prop in objType.GetProperties do begin
if Prop.GetClassType is TClassBase then
// do something special with base class properties
else
// standard functionality on all other properties
end;
end;
*)
end;
procedure IConfig.SetString(const Value: string);
begin
// Need the same as above
end;
end.
【问题讨论】:
-
你想做这样的事情吗? robstechcorner.blogspot.be/2009/10/…
标签: delphi properties attributes rtti