2014-04-16 111 views
4

德尔福RTTI设定值I类有这样根据属性值

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程序,以填补我的财产的价值,但我有问题。 我需要做什么?

+0

这将是更好,如果你发布真正的代码。要搞清楚SetCodeInt是什么是有点困难的。尤其是因为你从不称呼它。你需要解决你的问题,因为它目前需要我们阅读你的想法。也许有人能够做到这一点,但我们不应该这样做。 –

+0

我更新我的问题,明确我想做什么 –

回答

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; 
+0

非常感谢:) –

+1

如果您将'ctx.GetType(TypeInfo(TUserClass))'更改为'ctx.GetType(ClassType)',那么此代码也适用于类它来自'TUserClass',否则它只针对'TUserClass'。 –

+0

@Remy谢谢。顺便说一句,我会非常高兴你能做出如编辑一样明显的改进。 –