Delphi 2010: new RTTI setting value property for conditional value

TRTTIProperty.SetValue () accepts a TValue instance, but if the provided TValue instance is based on a different type, then the property, things explode.

eg.

TMyObject = class published property StringValue: string read FStringValue write FStringValue; end; procedure SetProperty(obj: TMyObject); var context: TRTTIContext; rtti: TRTTIType; prop: TRTTIProperty; value: TValue; begin context := TRTTIContext.Create; rtti := context.GetType(TMyObject); prop := rtti.GetProperty('StringValue'); value := 1000; prop.SetValue(obj, value); end; 

Trying to distinguish a value from a string will not work.

 prop.SetValue(obj, value.AsString); prop.SetValue(obj, value.Cast(prop.PropertyType.Handle)); 

Any ideas on how to solve this problem?

UPDATE:

Some of you are wondering why I want to assign an integer to a string, and I will try to explain. (In fact, it is more likely that I want to assign a string to an integer, but this is not so important ...)

What I'm trying to accomplish is to create a common "middle man" between gui and the model. I want to somehow bind a textedit field to a property. Instead of making such an average person for each model that I have, I was hoping that the new RTTI / TValue thing would work for me in some manner.

I am also new to generics, so I'm not sure how generics could help. Is it possible to create a generic instance at runtime with a dynamically resolved type, or do I need to know the compilation?

eg.

 TMyGeneric<T> = class end; procedure DoSomething( ); begin prop := rtti.getProperty('StringValue'); mygen := TMyGeneric<prop.PropertyType>.Create; //or mygen := TMyGeneric<someModel.Class>.Create; end; 

Perhaps the age of magic is yet to come ... I guess I can deal with several structures of a large building ...

+4
source share
3 answers

TValue is not an option. You can only read the data type that you "entered" into it.

TValue.Cast does not work because it has the same semantics as implicit types. You cannot assign an integer to a string or vice versa. But you can assign an integer to float, or you can assign an integer to int64.

+5
source

I canโ€™t try right now, but I would write:

  value := '1000'; prop.SetValue(obj, value); 
0
source

to try

prop.SetValue(obj, value.ToString)

But for me this is the same question as for Francois. Why do you want to set a property with a value of the wrong data type?

0
source

All Articles