How can I call TRttiProperty.SetValue for non-string properties when I have the value as a string?
I want to serialize an Object in Delphi and I'm using the new RTTI. Butwhen I load the values from the storage, they are retreived as string,s and TRttiProperty.SetValue needs a TValue as a second argument. Thus an exception is raised when I set the value of a property declared as a double to '5.1' or '5'
I also Tried using TValue.From()
method with no success.
here is a piece of code which explains where things go wrong.
var P: TRttiProperty;
....
// P now is the property which is declared as a double or integer
P.SetValue(Self, '3')开发者_开发技巧; //<-- this raises an exception.
EDIT: Question is how to get it to set the value of a property which isn't string type, using a string data type, but which contains valid data. (such as the above case)
Yeah, you're trying to assign '3' (a string) to a numeric property. The RTTI system doesn't do implicit type conversions. Try something like this:
procedure DeserializeProperty(P: TRttiProperty; s: string);
var
v: TValue;
begin
case p.PropertyType.TypeKind of
tkInteger: v := StrToInt(s);
tkFloat: v := StrToFloat(s);
tkString: v := s;
end;
p.SetValue(self, v);
end;
This is obviously not a finished product, but it should be enough to get you started.
精彩评论