2011-10-07 140 views
-1

您好我有這個代碼的問題:德爾福typinfo SetPropValue

unit Unit1; 

interface 

uses 
    Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, 
    Dialogs, ActnList, StdCtrls, Buttons, MSObjCtrls, StrUtils; 
type 
    Data = class(TObject) 
    FName : string; 
    FValue : string; 
    private 
    public 
    published 
    property Name : string read FName write FName; 
    property Value : string read FValue write FValue; 
    end; 
type 
    TForm1 = class(TForm) 
    edtResult : TMSObjectText; 
    btnGo : TMSBitBtn; 
    ActionList1 : TActionList; 
    acGo : TAction; 
    procedure acGoExecute(Sender : TObject); 
    private 
    procedure Split(Delimiter, S : string; Strings : TStrings); 
    public 
    { Public declarations } 
    end; 

var 
    Form1         : TForm1; 

implementation 

uses TypInfo; 

{$R *.dfm} 

procedure TForm1.Split(Delimiter, S : string; Strings : TStrings); 
var 
    P, OldP        : integer; 
    Token         : string; 
begin 
    if (Strings = nil) or (Length(S) = 0) or (Length(Delimiter) = 0) then 
    exit; 
    P := Pos(Delimiter, S); 
    OldP := 1; 
    while P > 0 do 
    begin 
    Token := Copy(S, OldP, P - OldP); 
    Strings.Add(Token); 

    OldP := P + 1; 
    P := PosEx(Delimiter, S, OldP); 
    end; 
    if P = 0 then 
    Strings.Add(Copy(S, OldP, Length(S))); 
end; 

procedure TForm1.acGoExecute(Sender : TObject); 
var 
    Lst, tmpLst       : TStringList; 
    i          : Integer; 
    Obj         : Data; 
    str         : string; 
begin 
    str := 'Name=Jordan Borisov;Value=man'; 
    Lst := TStringList.Create; 
    tmpLst := TStringList.Create; 
    Split(';', str, Lst); 
    Obj := Data.Create; 
    for i := 0 to Lst.Count - 1 do 
    begin 
    Split('=', Lst[i], tmpLst); 
    try 
     SetPropValue(Obj, tmpLst[0], tmpLst[1]); 
    except 
     ShowMessage(Format('Invalid property name %s', [tmpLst[0]])); 
    end; 

    tmpLst.Clear; 
    end; 
    edtResult.Text := 'Name[' + Obj.Name + '],Value[' + Obj.Value + ']'; 
end; 

end. 

有人能告訴我問題出在哪裏?

在此先感謝!

+0

如果您告訴我們什麼不起作用,您會得到更好的答案。它不會編譯?它不是做你想做的事嗎?問題是什麼? –

+0

對不起,我忘了。 問題是,在SetPropValue方法中,我嘗試爲類Data中的屬性Name設置一個新值,但每次都使用文本引發一個異常:Property Name不存在。 –

+0

需要在acGoExecute中釋放Lst和tmpLst。 –

回答

1

對於使用{$TYPEINFO ON}(或{$M+})指令編譯的類生成RTTI。 TObject不是其中之一;它開始於TPersistent。所以要麼從TPersistent派生你的類,要麼在你的代碼中使用{$M+}指令(在你的類的聲明之前)。

+0

儘管'TObject'沒有用{$ M +}編譯,編譯器在TObject後裔中看到'published'屬性時會自動添加{$ M +}(帶警告)。至少Delphi 2009是這樣做的。 – kludg

+0

@Serg:在XE/XE2中依然如此。這是[警告](http://docwiki.embarcadero.com/RADStudio/en/W1055_Published_caused_RTTI_(%24M%2B)_to_be_added_to_type _'%25s'_(德爾福))。謝謝(你的)信息。 –