Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi select object by unknown class type

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

like image 552
TreantBG Avatar asked Jan 18 '23 01:01

TreantBG


1 Answers

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;
like image 89
TLama Avatar answered Jan 25 '23 15:01

TLama