Hugues Van Landeghem
Hugues Van Landeghem

Reputation: 6808

Delphi RTTI Set Value by attribute value

I have class like this

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;

I want to use my SetCodeInt procedure to fill my property value but I have problem. What I have to do ?

Upvotes: 4

Views: 4517

Answers (1)

David Heffernan
David Heffernan

Reputation: 613461

You need a custom attribute class:

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;

I've chosen to make the value an integer which seems more appropriate than a string.

Then you define the properties like this:

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

Finally the implementation of SetCodeInt is:

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;

Upvotes: 6

Related Questions