PDA

View Full Version : Accesing propertys by name



SilverWarior
29-10-2011, 02:31 AM
Hi guys!
Is it posible to acces properties by name. I'm trying to create a function wich would be able to replace portion of text (property name) with value of certain property. The function would be similar to Format function for string formating, but would only take text as an input. For instance the function would replace "#i#MyValue# " portion of the input text with actual value from MyValue wich is an integer variable.

Stoney
29-10-2011, 02:58 AM
You could RTTI for that, it's quite easy once you get the hang of it. Assuming you use Delphi or FreePascal in Delphi mode, you need to set {M+} in your unit where you defined the class.
Only published properties work and the properties are case-sensitive.

To set a property using RTTI, look at this small example:


uses
typinfo;

[...]

{M+}
TMyClass = class
procedure SetProperty(const aName: String; aValue: AnsiString);
end;

[...]

procedure TelObject.SetPropertyStr(const aName: String; aValue: AnsiString);
begin
if not IsPublishedProp(aName) then Exit;

case PropType(Self, aName) of
tkInteger, tkInt64, tkQWord: SetOrdProp(Self, aName, StrToInt(aValue));
tkFloat: SetFloatProp(Self, tmpName, StrToFloat(aValue));
tkSString, tkLString, tkAString, tkWString, tkUString: SetStrProp(Self, aName, aValue);
tkVariant: SetVariantProp(Self, aName, aValue);
tkBool: SetOrdProp(Self, aName, Ord(LowerCase(aValue) = 'true'));
end;
end;


This example checks if the property exists and sets the property according to its type. So if the property is an integer, it will set as an integer (even though aValue is a string) and the same goes for every other type.

User137
29-10-2011, 02:21 PM
Would StringReplace do the work?
http://www.delphibasics.co.uk/RTL.asp?Name=StringReplace