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 ...