通过属性值设置Delphi RTTI中的Set值

4
我有一个类像这样
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过程来填充我的属性值,但是我遇到了问题。我该怎么办?

最好您发布真实的代码。现在很难理解SetCodeInt的作用,尤其是因为您从未调用它。您需要修正您的问题,因为目前我们需要猜测您的意图。或许有人能够猜中,但我们不应该这样做。 - David Heffernan
我更新了我的问题,以明确我想要做什么。 - Hugues Van Landeghem
1个回答

6
您需要一个自定义属性类:
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;

1
如果你将 ctx.GetType(TypeInfo(TUserClass)) 更改为 ctx.GetType(ClassType),那么这段代码也适用于从 TUserClass 派生的类,否则它仅适用于 TUserClass - Remy Lebeau
@Remy 谢谢。顺便说一下,如果你能编辑并做出这样一个明显的改进,我会非常高兴的。 - David Heffernan
@DavidHeffernan: 我只在有充分理由的情况下编辑别人的答案。在这种情况下,没有迹象表明TUserClass从何处派生。我只是指出了一个可能的调整,而不是要求。 - Remy Lebeau

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接