Delphi RTTI按属性值设置值
我有这样的课Delphi RTTI按属性值设置值,delphi,attributes,rtti,Delphi,Attributes,Rtti,我有这样的课 TuserClass = class private FUtilisateurCode: string; FUtilisateurCle: string; public procedure SetCodeInt(ACode: string; AValue: string); published [CodeInt('2800')] property UtilisateurCode: String read FUtilisateurCode write FUtilis
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;
如果你发布真实的代码会更好。要弄清楚
SetCodeInt
的全部内容有点困难。不仅仅是因为你从不打电话。你需要修正你的问题,因为它目前需要我们来了解你的想法。可能有人能够做到这一点,但我们不应该这样做。如果您将ctx.GetType(TypeInfo(TUserClass))
更改为ctx.GetType(ClassType)
,我将更新我的问题,以明确我想要做什么,然后此代码也将适用于从TUserClass
派生的类,否则它只针对TUserClass
。@Remy谢谢。顺便说一句,如果你能做出如此明显的修改,我会非常高兴的。@DavidHeffernan:我只会在有充分理由的情况下编辑人们的答案。在这种情况下,没有迹象表明TUserClass
是从中派生出来的。我只是指出一个可能的调整,而不是要求。