Delphi RTTI按属性值设置值

我有这样的课

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 API HOOK完全说明》这篇文章,基本上都...
  从网上看到《Delphi API HOOK完全说明》这篇文章,基本上...
ffmpeg 是一套强大的开源的多媒体库 一般都是用 c/c+&#x...
32位CPU所含有的寄存器有:4个数据寄存器(EAX、EBX、ECX和ED...
1 mov dst, src dst是目的操作数,src是源操作数,指令实现的...