I have a few different classes which origin is a another class. I have one property that is extended to all other classes. But different classes handle this property differently. So i want to do this:
TClass(ObjectPointer).Property:=Value;
But TClass is unknown class type
Can i do something like that:
ObjectPointer.ClassType(ObjectPointer).Property:=Value
or this
var
ClassRef: TClass;
begin
ClassRef := Sender.ClassType;
ClassRef(ObjectPointer).DoStuff
end;
Is there way to do this in delphi without using if statement
Please note, the code from this post will work only for published properties!
To answer your question if there's a way to set a property value without using if statement, check the following overloaded functions.
The first one is for char, string, variant, integer, 64-bit integer, float, enumeration, set and dynamic array type of properties (phew). The second one is just for class type properties. Both will return True if given property exists and the value or object instance is successfuly assigned, False otherwise:
uses
TypInfo;
function TrySetPropValue(AInstance: TObject; const APropName: string;
const AValue: Variant): Boolean; overload;
begin
Result := True;
try
SetPropValue(AInstance, APropName, AValue);
except
Result := False;
end;
end;
function TrySetPropValue(AInstance: TObject; const APropName: string;
AValue: TObject): Boolean; overload;
begin
Result := True;
try
SetObjectProp(AInstance, APropName, AValue);
except
Result := False;
end;
end;
And the usage; when the Memo1.Lines
is set the, the second version of TrySetPropValue
is called:
procedure TForm1.Button1Click(Sender: TObject);
var
Strings: TStringList;
begin
TrySetPropValue(Memo1, 'Width', 250);
TrySetPropValue(Memo1, 'Height', 100);
TrySetPropValue(Memo1, 'ScrollBars', ssBoth);
Strings := TStringList.Create;
try
Strings.Add('First line');
Strings.Add('Second line');
TrySetPropValue(Memo1, 'Lines', Strings);
finally
Strings.Free;
end;
if not TrySetPropValue(Memo1, 'Height', 'String') then
ShowMessage('Property doesn''t exist or the value is invalid...');
if not TrySetPropValue(Memo1, 'Nonsense', 123456) then
ShowMessage('Property doesn''t exist or the value is invalid...');
end;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With