gpt4 book ai didi

Delphi RTTI 通过属性值设置值

转载 作者:行者123 更新时间:2023-12-03 15:25:16 27 4
gpt4 key购买 nike

我有这样的类(class)

TuserClass = class
private
FUtilisateurCode: string;
FUtilisateurCle: string;
public
procedure SetCodeInt(ACode: string; AValue: string);
published
[CodeInt('2800')]
property UtilisateurCode: String read FUtilisateurCode write FUtilisateurCode;
[CodeInt('2801')]
property UtilisateurCle: String read FUtilisateurCle write FUtilisateurCle;
end;

procedure TuserClass.SetCodeInt(ACode: string; AValue: string);
begin
// what I want to is making this by RTTI to set good value to good CodeInt
if ACode = '2800' then FutilisateurCode := AValue
else if ACode = '2801' then FUtilisateurCle := AValue;
end;

我想使用我的 SetCodeInt 过程来填充我的属性值,但我有问题。我必须做什么?

最佳答案

您需要一个自定义属性类:

type
CodeIntAttribute = class(TCustomAttribute)
private
FValue: Integer;
public
constructor Create(AValue: Integer);
property Value: Integer read FValue;
end;
....
constructor CodeIntAttribute.Create(AValue: Integer);
begin
inherited Create;
FValue := AValue;
end;

我选择将值设置为整数,这似乎比字符串更合适。

然后定义如下属性:

[CodeInt(2800)]
property UtilisateurCode: string read FUtilisateurCode write FUtilisateurCode;
[CodeInt(2801)]
property UtilisateurCle: string read FUtilisateurCle write FUtilisateurCle;

最后SetCodeInt的实现是:

procedure TUserClass.SetCodeInt(ACode: Integer; AValue: string);
var
ctx: TRttiContext;
typ: TRttiType;
prop: TRttiProperty;
attr: TCustomAttribute;
codeattr: CodeIntAttribute;
begin
typ := ctx.GetType(ClassType);
for prop in typ.GetProperties do
for attr in prop.GetAttributes do
if attr is CodeIntAttribute then
if CodeIntAttribute(attr).Value=ACode then
begin
prop.SetValue(Self, TValue.From(AValue));
exit;
end;
raise Exception.CreateFmt('Property with code %d not found.', [ACode]);
end;

关于Delphi RTTI 通过属性值设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23110881/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com