delphi typinfo SetPropValue
您好,我对此代码有问题:delphi typinfo SetPropValue,delphi,reflection,Delphi,Reflection,您好,我对此代码有问题: 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 : str
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.
谁能告诉我哪里出了问题
提前谢谢 RTTI是为使用(或
{$M+}
指令编译的类生成的TObject
不是其中之一;它从持续的开始。因此,要么从TPersistent派生类,要么在代码中使用{$M+}
指令(在声明类之前)。如果您告诉我们什么不起作用,您会得到更好的答案。它不编译吗?它不是你想要的吗?什么问题?对不起,我忘了。问题是,在方法SetPropValue中,我尝试在类数据中为属性名设置一个新值,但每次都会出现一个异常:属性名不存在。Lst和tmpLst需要在acGoExecute中释放。我复制/粘贴了您的代码,并且它在我这方面工作正常(我只是用普通的替换了MSObjCtrl)。因此,代码本身没有问题。一些项目选项可能?可能有异常的确切文本会有帮助。虽然TObject
不是用{$M+}编译的,编译器会自动添加{$M+}当它在TObject
子代中看到published
属性时(带有警告)。至少Delphi 2009会这样做。@Serg:在XE/XE2中仍然是一样的。这是最新的。感谢您提供的信息。